If i have [Required(AllowEmptyStrings = true)] declaration in my view model the validation is always triggered on empty inputs. I found the article which explains why it happens. Do you know if there is a fix available? If not, how do you handle it?
If i have [Required(AllowEmptyStrings = true)] declaration in my view model the validation is
Share
Note: I’m assuming you have AllowEmptyStrings = true because you’re also using your view model outside of a web scenario; otherwise it doesn’t seem like there’s much of a point to having a Required attribute that allows empty strings in a web scenario.
There are three steps to handle this:
Step 1: The custom attribute adapter
I modified the RequiredAttributeAdapter to add in that logic:
Step 2. Register this in your global.asax / Application_Start()
Step 3. Override the jQuery “required” validation function
This is done using the jQuery.validator.addMethod() call, adding our custom logic and then calling the original function – you can read more about this approach here. If you are using this throughout your site, perhaps in a script file referenced from your _Layout.cshtml. Here’s a sample script block you can drop in a page to test: