With the new unobtrusive JavaScript validations libraries included in ASP.Net MVC, it has become just so easy to add validation to any client input field, whether or not the field is backed by a model that exposes data annotations.
When you have data annotations and a model backing the input field, the framework will create the unobtrusive JavaScript for you, but where you don’t have those then it isn’t that hard to still have a consistent validation experience.
To add unobtrusive validation to an element, you add the following HTML attributes:
data-val = truedata-val-(required|regex|range|equalto|remote|length|number)="your error message"
and, depending on the validation message set the values of corresponding data-val- attribute listed below:
data-val-regex-patterndata-val-range-mindata-val-range-maxdata-val-equalto-otherdata-val-remote-urldata-val-remote-typedata-val-remote-additionalfielddata-val-length-mindata-val-length-max
Make sure that you have included the script references to
- jquery.validate.js
- jquery.validate.unobtrusive.js
and you are good to go….
