We all know the .NET Framework comes with a bunch of easy to use validators, targeting most common validation purposes:
But what if we need validation logic not covered from the standard validators?
Where other validators are of no help... there comes the CustomValidator.
CustomValidator is often overlooked, since id does nothing unless we add some code.
Well, this should not be so hard... we are programmers, right?
What for example if we need our users to fill at least one of to textboxes in a form like this?
<asp:TextBox runat="server" ID="AlternativeTextBox1" /><br />
<asp:TextBox runat="server" ID="AlternativeTextBox2" /><br />
<asp:Button runat="server" ID="SubmitButton" Text="Submit" onclick="SubmitButton_Click" />
We can handle this with a custom validator:
<asp:CustomValidator runat="server" ID="AlternativeCustomValidator" ErrorMessage="Fill at least one" onservervalidate="AlternativeCustomValidator_ServerValidate" />
A simple server-side custom validation event handler could look like this:
protected void AlternativeCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = AlternativeTextBox1.Text.Trim().Length > 0 || AlternativeTextBox2.Text.Trim().Length > 0;
}
This is nothing special. Most of the times I've seen people overlooking client-side validation.
The CustomValidator exposes a ClientValidationFunction property we can point to the name of a custom javascript function.
In our sample we would set it like this:
<asp:CustomValidator runat="server" ID="AlternativeCustomValidator" ErrorMessage="Fill at least one" onservervalidate="AlternativeCustomValidator_ServerValidate" ClientValidationFunction="alternativeTextboxValidation" />
And finally we would need to add that javascript function to our page:
<script type=
"text/javascript">
function alternativeTextboxValidation(sender, args) {
args.IsValid = document.getElementById('<%= AlternativeTextBox1.ClientID %>').value != "" || document.getElementById('<%= AlternativeTextBox2.ClientID %>').value != "";
}
</script>
Well... we are missing the trim() function here... but it's just a sample
.
Now we have a full client/server-side validation logic for our CustomValidator.
NOTE: always keep in mind client-side validation is a "nice-to-have", server-side validation is a "must" !