Friday, July 20, 2012

Using the CustomValidator’s ClientValidationFunction

You can use the CustomValidator by just implementing the OnServerValidate event, but any other validation controls that are validated client side will need to be valid before the CustomValidator will be used.  Doing this causes a postback to validate the CustomValidator and as it’s not client side the validation message will not be shown in a ValidationSummary.
Here is a CustomValidator to validate that a checkbox is checked:
<asp:customvalidator errormessage="You must agree." id="cvTerms" onservervalidate="cvTerms_ServerValidate" runat="server">
</asp:customvalidator>

Usually with validators you would set the ControlToValidate property to the ID of the control you want to validate, but this doesn’t work for a checkbox, so I will explicitly reference the checkbox in the event handler:
protected void cvTerms_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = cbTerms.Checked;
}


ServerValidateEventArgs has two properties; IsValid and Value.  IsValid is set in the handler depending on if the checkbox is checked.  Value is not used here due to not setting the ControlToValidate property.  If the ControlToValidate property was set to a TextBox, then args.Value would be the text value from the TextBox.
This all works nicely, but it would be good to do this validation client side, also allowing the error to show in a ValidationSummary.  To do this I have created a JavaScript function to do the client side validation:
function cvTerms_ClientValidate(source, args)
{
    args.IsValid = document.getElementById('<%= cbTerms.ClientID %>').checked;
}


I also need to set the ClientValidationFunction property of the CustomValidator to the name of my JavaScript function.
In JavaScript args works very much in the same way as it does in C#.  I am setting args.IsValid based on whether the checkbox is checked.
Now validation will work at client side, and if JavaScript is disabled, the server side event handler will be used.  Below is another simple example that ensures a TextBox contains no more than 1000 words.
ASP
<asp:CustomValidator ID="cvText"
                     ControlToValidate="txtText"
                     runat="server"
                     ErrorMessage="Your text is over 1000 words."
                     OnServerValidate="cvtext_ServerValidate"
                     ClientValidationFunction="cvText_ClientValidate" />


C#
protected void cvText_ServerValidate(object source, ServerValidateEventArgs args)
{
    string[] numOfWords = args.Value.Split(new char[] { ' ' });
    args.IsValid = numOfWords.Length <= 1000;
}

JavaScript
function custStory_ServerValidate(source, args)
{
    var numOfWords = args.Value.split(" ");
    args.IsValid = numOfWords.length <= 1000;
}
ref : http://www.joe-stevens.com/2009/08/12/using-the-customvalidators-clientvalidationfunction/

No comments:

Post a Comment