Arbitrary client side validation in ASP.Net MVC 3

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 = true
  • data-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-pattern
  • data-val-range-min
  • data-val-range-max
  • data-val-equalto-other
  • data-val-remote-url
  • data-val-remote-type
  • data-val-remote-additionalfield
  • data-val-length-min
  • data-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….

This entry was posted in ASP.Net MVC and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s