/ asp.net

Using Parsley Validation in Asp.Net 5

Asp.Net always comes with built-in support for jQuery Unobtrusive Validation. It is based on jQuery validation. I like it and use it in a number of places. But there are times I like to use parsley validation mainly because of the themes. I know it can be done with jQuery validation but somehow parsley seems superior in my sight.

Asp.Net generates validation attributes in HTML from the C# models that you write. You can Google about that if you do not already know it. In the newer version of Asp.Net, there is still no way to plug in a custom generator if you want to use anything else other than jQuery validation. So I went digging into the code to find how I could plug in some different generator. I may have done it the wrong way but it worked. In case someone else has a better way of doing this, hit me up in the comments or mail.

Like I said, I do not dislike jQuery validation and thus, would like to retain it. So in my little hack, I used an ActionAttribute when I really want to override the jQuery generation. Otherwise, the jQuery validation attributes are generated by default.

I did this in just 3 commits as you can see in the Github repo and the image below.

all 3 commits

First, the validation attributes for parsley validation are prefixed by data-parsley-. Some validation attributes have different names. This is handled by the Parsley generator file.

Second, to switch between the inbuilt jQuery validation and parsley validation, use the ViewData of the current view context. Store a variable in there that we shall check later. As mentioned earlier we use an action attribute named UseParsleyValidationAttribute available here.

Thirdly, we must override the generator used in the MVC pipeline. We have to replace the IHtmlGenerator service whose usual implementation is DefaultHtmlGenerator with CustomHtmlGenerator here. Notice the lines of code that do the switching between the two validations. The service replacement is done in the application startup file, have a look here in case you can't see it.

Fourthly, use the attribute in the controller for both the HttpGet and HttpPost methods in the usual samples for Asp.Net. In the sample it is here and here.

Fifthly, in the views remember to include the right scripts. I did so using a partial view named _ParsleyValidationScripts. If you wish not to write any javascript code to validate the form, remember to add the attribute data-parsley-validate="true" in the form as shown here.

sample view

In five easy steps, that is done.


The partial view that adds the validation scripts for parsley uses local files for debugging, and CDN files for the production and staging environments as is the norm in the new Asp.Net. I have also added the tests for the CDN link before falling back to the local, see it here


I did not include any styles since I wanted the changes to be as few as possible. I left that for you!

Happy coding!