JQuery Validation in MVC 5, Visual Studio 2015

Step 1:  Decorate the required parameters of your model.  I’m not going to go into all the different types of validation MVC offers (Required, Maximum Characters, Regular Expressions, etc…).  For the sake of this example, I’m going to assume we only want to make each field REQUIRED.  We need to decorate each required parameter of our Model as “Required” and assign an Error Message (see the example image below):
ModelDecorated
Notice, I have 4 attributes of the MODELCREATEASSET class decorated as required?  Good.  Moving on.
Step 2:  We need to add the Validation Error Message to the View.  This is pretty straight forward as seen here:
ViewDecorations
What you’re looking for is the @Html.ValidationMessageFor(x => x.Model) under each @Html.EditorFor(x => x.Model).  Yes, I know there are tables in there.  It’s not my fault.  I only recently found out about Bootstrap.
Step 3:  We need to assign the “cancel” class to the Cancel button of the form.  Most forms have a submit/ok button and a cancel button.  I have a cancel button in each of my forms as my users complain if one isn’t there.  If you don’t add the “cancel” class to the button, it triggers validation whenever you click either “Submit” or “Cancel”.  Which can be downright irritating if you’re the user trying to cancel out of a form, but forced to enter garbage data into required fields just to go back.  And yes, adding the cancel class to the button is exactly like what I just described.
ViewSubmitCancel
I haven’t actually created a “cancel” class in my CSS file.  I just referenced it here.
Step 4:  We need to add the proper JQuery files to your project.  This is what took me so damn long to figure out.  There are real inconsistency issues between different versions of JQuery and versions that have/had bugs in them.  The safest way to be certain you load the correct versions of JQuery.Validation and JQuery.Unobtrusive.Validation is to add them using NuGet in Visual Studio.  I have Visual Studio 2013, so your screen may look a bit different from mine, but here are images of the packages that need to be added:
NuGet Validation Packages
Add both of these to your project.  Lastly, you need to reference them.  You can add them to your bundles or you can add them to the head of your Layout page like so:
JQuery Files
That’s it.  If you’ve done all of that, you should have a working set of client-side JQuery form validators running.  If you’ve run into a problem, it’s most likely a JQuery file version issue (or I’ve forgotten a step in my description above).  Try using all of the file versions I have:
  • JQuery: 1.9.1
  • JQuery Validate: 1.11.1
  • JQuery Unobtrusive: Grr… this one doesn’t have a version embedded into the file.  Just make sure you grab the same file from NuGet that I did.
Good luck validating your users input!

Comentarios

Entradas populares