Use and Manipulate Asp.Net Validators with jQuery and/or Javascript

Asp.Net has some great validation included - no need to learn new validation, just grab them with client-side scripting

The problem I found when going into jQuery validation, is that they mostly seem to assume that you can have more than one form on your page; which, for us Asp.Net devs, is not the case. After some digging, I figured out how to use the current validators which I am already familiar with (RegularExpressionValidator, RequiredFieldValidator, etc.) and just hook into them with javascript; no need to reinvent the wheel. It is very easy, and we don't lose the server-side validation that is so great with the Asp.Net validators (if you call on it that is).

want to make a certain validator(s) fire?

Let's say I have a RequiredFieldValidator named 'rfvFirst' and I want it to test for validation on the click event of the element with id 'some_link'. With jQuery, this is what I would do:
$("#some_link").click(function() {
    ValidatorValidate($("#<%= rfvFirst.ClientID %>")[0]);
});

Now, the ErrorMessage of 'rfvFirst' will show if it is not valid - it will behave just as if you tried to submit the form, but just for that validator itself. Notice that I am using <%= rfvFirst.ClientID %> which will pull the crazy Asp.Net id that is produced in Asp.net which is often something strange like 'ctl00_ContentPlaceHolder1_rfvFirst'.  Now, if you want to use a class or something else to select the Validators, that is fine too.  This will fire all of the Validators that have the CssClass 'fire':
$(".fire").each(function() {
    ValidatorValidate($(this)[0]);
});

want to have a button/link cause validation and only work if the page is valid?

For this, you need to make sure your validators each have a ValidationGroup set. In this example I am attaching it to a button with id 'submit' and the ValidationGroup 'new'. Simply attach the click event to Page_ClientValidate() method:
$("#submit").click(function() {
    return Page_ClientValidate('new');
});

This was the only method I found that actually returned something that could be used to tell if the page was valid (I am far from a JS pro). There is likely more ways to do this and I am interested in any that people have found!

want to stroll through the validators?

The are all held in an object (array) 'Page_Validators' and you can access it like any other array, looping or whatever. This will look through and output into the 'report' element the ids of all the Validators you have on your page:
for(var i=0,len=Page_Validators.length;i<len;++i){
    $("#report").append($(Page_Validators[i]).attr('id'));
    $("#report").append("<br />");
}

Finding web hosting reviews is the first step when you plan to build a website. It will help you ensure a great looking site.
Comments are closed