I have two logical groups of input fields I need to validate separately using JQuery Validation however since I am using ASP.Net WebForms I’m restricted to having just one form tag on the page.
I’ve implemented validation groups even though I have one form using the following technique from Dave Ward’s blog post. This works perfectly.
To bind the validation event to the ASP.Net form looks as follows:
$("#aspnetForm").validate({
onsubmit: false,
ignore: ":hidden",
errorClass: 'dynamic-class'
});
I need to take this further by having a different errorClass value based on whether I am trying to submit (and validate) Form A or Form B. E.g. “Form A” would have “error-class-a” and “Form B” would have “error-class-B”. I actually want to do this with other validation settings such as errorPlacement and errorElement but I’ve tried to keep this explanation simple.
Is there a way I can inject this behaviour without having to hack away at the JQuery Validation plugin source code?
I started by adding validation groups (as per Dave Ward’s blog post) so I had two logical groups. After a VERY long look into the JQuery Validate documentation and source code I narrowed the investigation down to a single function: showErrors(). This gets called each time before any error is potentially displayed whether it is on the form submission event or a blur event of one of the elements. By changing the settings accordingly this ensures the correct display settings are always used for the right element.
In the code below one validation group is set to display errors in a UL list summary and the other inline and with a different css class. I’ve extended the showErrors() function to dynamically switch the error settings based on which validation group the element that has an error is contained in. You could probably take this further and bind the settings to the validation container to avoid the clunky IF statement, but I’ve used the simple version below as it better illustrates the solution. Finally I call the defaultShowErrors() which as one would expect calls the default function in the validate framework.
This does exactly what I was looking for since it means I do not have to make any changes to the validate framework. This is demonstrated in the full working example below where I am using a CDN for JQuery and JQuery.Validate!
Full Code
If this could be further improved please jump in and edit the code.