First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

Validators are a great part of the ASP.NET framework: they provide a standardized and easy way to add validation to form fields. But even if the framework provides different kinds of validators, there are so many different validations patterns that sometimes you have to write custom code to match your specific requirements.

I wrote a post a few months ago about how to write a custom validator for a Checkbox list, but I was dealing with a completely new validation pattern. But what if I only want to enable the validation of certain field based on certain conditions? Or if I want to validate based on an event that is not the OnChange event of the form field? And all of this while keeping the standard validation logic?

If the condition can be determined in the code-behind it's easy:

//Disable server side validation
myRequiredFieldValidator.Enabled = false;
//Disable client side validation
myRequiredFieldValidator.EnableClientScript = false;

But what if I want to enable the validator from javascript? I didn't find anything online about this so I debugged the ASP.NET js validation library to look for the method that enables the validation, and for the one that forces the validation check.

Enable a validator via javascript

The method to enable or disable a validator is:

function ValidatorEnable(val, enable)

where val is the reference to the <span> element that the validator uses to render the error message, and enable is a boolean to tell the method whether to enable or disable the validation.

Force a validation via javascript

In case you want to ask to a validator to do his job:

function ValidatorValidate(val, validationGroup, event)

val is again the reference to the validator <span>, validationGroup is the name of the validation group of the element that is triggering the validation, event is the reference to the event that triggered the validation. But only the first parameter is useful when you want to force the validation, since the others are used only by the standard validation of ASP.NET.

A real life example

Let's see a example from the code I'm writing for one of the new features of Subtext.
Imagine you have this snippet of HTML code:

<asp:DropDownList ID="ddlMimeType" runat="server">
   <asp:ListItem Value="mp3">audio/mpeg</asp:ListItem>
   <asp:ListItem Value="wma">audio/wma</asp:ListItem>
   <asp:ListItem Value="other">Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox id="txbOtherMimetype" runat="server" />
<asp:RequiredFieldValidator id="valOtherMimetypeRequired" runat="server"
                   ControlToValidate="txbOtherMimetype" ForeColor="#990066"
                   ErrorMessage="You have to specify a custom mimetype." />

And you want to enable the valOtherMimeTypeRequired validator only when the option selected in the drop down is "other".

Using jQuery here is the javascript code to do the job:

<script type="text/javascript">
$(document).ready(function()
{
  $("#<%= ddlMimeType.ClientID %>").change(function() 
  {
    toggleOtherMimeType(this);
  });
}

function toggleOtherMimeType(elem)
{
  if(elem!=undefined) 
  {
    if(elem.value=="other")
    {
      $("#<%= txbEnclosureOtherMimetype.ClientID %>").show();
      ValidatorEnable($("#<%= valEncOtherMimetypeRequired.ClientID %>")[0], true);
    }
    else
    {
      $("#<%= txbEnclosureOtherMimetype.ClientID %>").hide();
      ValidatorEnable($("#<%= valEncOtherMimetypeRequired.ClientID %>")[0], false);
    }
  }
}
</script>

Notice the <%= ddlMimeType.ClientID %> to select a server-side control using the automatically generated client ID and the $("#elemendId")[0] to get the real DOM element and not the jQuery wrapper around it.

And in case I wanted to force the validation I should have written:

ValidatorValidate($("#<%= valEncOtherMimeTypeRequired.ClientID %>")[0]);

It took me a while to find out this method name. I hope this will save you a bit of the time I spent hunting down the names using Firebug.

kick it on DotNetKicks.com

Technorati Tag: ,,

posted on Wednesday, May 14, 2008 2:11 AM

Comments on this entry:

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Filippo Macchi at 5/14/2008 9:12 AM

Hi Simone, I've read your post and it's very interesting. I'm tring to test something about validatin in js.
I have a question about your code, what's the toggleEnclosureBox(); function?

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Simone at 5/14/2008 9:46 AM

Hi Filippo,
the toggleEnclosureBox() function is a function I have in my real code, but that I didn't wrote here because it's not relevant for the sample... and I forgot to remove the call to it.
Thank you for noting it, I just edited the sample code snippet

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by roberto at 5/14/2008 1:49 PM

I'm reading few docs on jQuery these days;
found it very powerfull.
I still haven't use it in real life. ;(
thank you for your example.

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by reha at 5/15/2008 7:05 AM

we have wrote the java scripts in xml and that javascripts contains validations were i need to disable the one of the validations in one webform we r using. but we have call those scripts in all other forms.
kindly reply in advance.

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Richard Cook at 5/16/2008 8:44 AM

Hi,

FYI. These functions, ValidateEnable and ValidatorValidate can be found in the ms help in visual studio. Here is the URL that is shown in ms-help.

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEV.v10.en/dnaspp/html/aspplusvalid.htm

Hope this helps,
Rich

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Simone at 5/16/2008 3:52 PM

Hi Richard,
I never find a reference to that (even because I didn't know the name of the methods I was looking for before debugging the code).
It's a real in-depth article, thank you for sharing.

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Jereme Guenther at 5/21/2008 10:04 PM

Speaking of client-side validation... I am having trouble getting a validator that has been assigned a ValidationGroup to do client-side validation.

If I remove the ValidationGroup assignement code:
oReq.ValidationGroup = "InputErrors";

then it works fine. From everything I have read, including your article, it looks like I should be able to have a validationgroup and client-side validation.

I have set both the ValidationSummary and the RequiredFieldValidator control's EnableClientScript attribute to true but it doesn't seem to make a difference. Any ideas?

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Mohamed Ahmed Meligy at 5/31/2008 4:43 PM

This's not about jQuery though. The point is the ASP.NET validators client side functions.

Thanks Richard Cook for referring to the list of those.
Unfortunately the link no longer works (VS2008 at least), and the corresponding online link (found in many forums) doesn't work as well.

However, the list is available on this MSDN page:
http://msdn.microsoft.com/en-us/library/aa479045.aspx#aspplusvalid_properties
See "Client-Side APIs".

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by christoff at 6/26/2008 2:05 AM

What if you're trying to validate dropdowns on a page where you don't necessarily know the ID of the control at design time?
Our application dynamically generates dropdowns at page load and uses ID's from a database as the id's for the dropdowns. In my validation ruleset, I'd like to have all dropdowns validated, or even dropdowns that can be matched to a partial ID that I can append to the generated one.
Any suggestions to help solve this issue? I've been googling, but all the samples I find all use ID's as the rule identifier.

Thanks in advance.

# re: How to manage ASP.NET validation from Javascript with jQuery

Left by Simone at 6/26/2008 10:44 PM

@Christoff:
you can add validation to dynamically added DDL.. How are you adding them? With a repeater or gridview?
If you are using the ID in the db you are not creating <asp:dropdown> but only standard HTML dropdown lists.
I'm not sure these can be validated using the asp.net validators.
Anyway, jQuery allow you to select elements based on many rules: you can either select all ddl, or based on part of the name...
Have a look at this page for the list of all selectors: http://docs.jquery.com/Selector

Comments have been closed on this topic.