Scenario
Lets imagine a scenario where we have 2 input boxes and we need to validate that atleast 1 of them should contain some value.
Solution
Asp.net CustomValidator comes handy here. Here is the code which would help us validate this simple scenario:
All works fine except that the validation occurs on the server side. What if we also want this validation from the client side ?
Its simple, create a client side function to validate the same scenario and specify the name of that function in the ‘ClientValidationFunction’ property of the CustomValidator.
<asp:CustomValidator ID="validateAddress" runat="server"
ErrorMessage="Please enter atleast 1 Address"
ClientValidationFunction="validateAtLeastOneAddressHasData"
OnServerValidate="validateAddress_ServerValidate1">
</asp:CustomValidator>
This enables the client side validation but there are still 2 issues with the above code :
1) There is no trimming happening in the client side validation code
2) The client side validation is fired only on the button click event.
For trimming there is a function provided by the asp.net validation scripts named ‘ValidatorTrim’ which is kind of hidden and only available once you start the page. This is how we can use it :
textBox1Value = ValidatorTrim(textBox1Value);
textBox2Value = ValidatorTrim(textBox2Value);
Now for the second issue, ideally the client side validation script should be fired on the onblur() event of any of the textboxes. To do that we would have to hookup the textboxes with the CustomValidator.
Hooking the first textbox is simple. Just specify it in the ControlToValidate property and set the ‘ValidateEmptyText’ property of the CustomValidator to true.
<asp:CustomValidator ID="validateAddress" runat="server"
ErrorMessage="Please enter atleast 1 Address"
ClientValidationFunction="validateAtLeastOneAddressHasData"
OnServerValidate="validateAddress_ServerValidate1"
ControlToValidate="txtAddress1"
ValidateEmptyText="True" >
</asp:CustomValidator>
For hooking the second textbox we would have to use a startup script function 'ValidatorHookupControlID as below :
<script type="text/javascript">
ValidatorHookupControlID ( '<% = txtAddress2.ClientID %>',
document.getElementById('<% =validateAddress.ClientID %>')
);
</script>