Introduction
This article shows how to build a custom validator and customize the error messages based on different conditions, as well as add a validation summary control and display error messages. This is very helpful if you have a lengthy form and you need to scroll down to hit a Submit button to validate the entire form. If the validation summary doesn't show the error message, the user could be confused. By default, the custom validator control doesn't render the error message to the validation summary control.
Background
I was working on a lengthy form that had various custom validators, as we had controls that needed to be validated differently based on what the user selected. After designing the form, I found that upon hitting the Submit button I had to scroll back up to check the error messages. So, I decided to design my own custom validator to display error messages based on selections.
Using the Code
As you can see in the picture above, I've created a sample project that holds the custom validator MyValidatorControl
, which I'll be discussing soon. What this page does is:
- When you check the >20,000.00 check box and enter any invalid value, it shows the error message "* >20000 required"
- When a check box is unchecked and an invalid value is entered (i.e. a negative value or a non-numeric value), it shows the error message "* >0 and <20000"
- The error message is displayed in both the custom validation control and the validation summary
I created a web custom control and called it MyValidatorControl
. I compiled it in the assembly MyValidatorControl.dll. The source code for MyValidatorControl.dll is available for download in MyValidatorControl.zip.
In the function EvaluateIsValid()
, the ControltoValidate
control (in this case, a text box) value is validated based on the check box selection. The property Text()
returns a different message, as well.
Public Class MyValidator
Inherits CustomValidator
Private sGT20 As String
Private sLT20 As String
Private bChked As Boolean = False
Property Greaterthan20Text() As String
Get
Return sGT20
End Get
Set(ByVal value As String)
sGT20 = value
End Set
End Property
Property Lessthan20Text() As String
Get
Return sLT20
End Get
Set(ByVal value As String)
sLT20 = value
End Set
End Property
Property isGT20Checked() As Boolean
Get
Return ViewState("bChked")
End Get
Set(ByVal value As Boolean)
ViewState("bChked") = value
End Set
End Property
<Bindable(True), Category("Appearance"), _
DefaultValue(""), Localizable(True)>_
Overrides Property Text() As String
Get
If isGT20Checked Then
Return Greaterthan20Text
Else
Return Lessthan20Text
End If
End Get
Set(ByVal Value As String)
If isGT20Checked Then
Greaterthan20Text = Value
Else
Lessthan20Text = Value
End If
End Set
End Property
Protected Overrides Function EvaluateIsValid() As Boolean
If Not IsNumeric(Me.GetControlValidationValue(_
Me.ControlToValidate)) Then
Return False
End If
If isGT20Checked And CInt(_
Me.GetControlValidationValue(_
Me.ControlToValidate)) < 20000 Then
Return False
ElseIf Not isGT20Checked And CInt(_
Me.GetControlValidationValue(Me.ControlToValidate)) < 0 Then
Return False
End If
Return True
End Function
End Class
Modify this as per your requirement and compile it into an assembly (DLL file). Create a website called "Project1" -- or you can call it anything you want -- and add the compiled assembly to the Project1 bin folder. You can copy and place the DLL in the bin folder or you can do it via the "Add reference" feature in Visual Studio.
Open Default.aspx in design mode and place a text box, RequiredFieldValidator
, a check box, a ValidationSummary
control and the custom validator MyValidator
. The properties Greaterthan20Text
and Lessthan20Text
are preset for the control.
<% @ Register Assembly="MyValidatorControl"
Namespace="MyValidatorControl" TagPrefix="cc1" %>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvalidator"
runat="server" ErrorMessage="* Required"
ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<cc1:MyValidator id="MyValidator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="* > 0"
Greaterthan20Text="* >20000 required"
Lessthan20Text="* >0 required and <20000 "
ClientValidationFunction="ValidateGT20Function"
ValidateEmptyText="True">
* >0 required and <20000
</cc1:MyValidator>
<br/>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True"
Text="> 20,000.00" Width="98px" />
<br/>
<br/>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" DisplayMode="List"
ShowSummary="false" />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
The check box control property AutoPostBack
should be set to true
. The event CheckedChanged
is handled in Default.aspx.vb.
Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
MyValidator1.isGT20Checked = CheckBox1.Checked
End Sub
The MyValidator
control has a property called ClientValidationfunction
that is set to ValidateGT20Function
. This will be the client-side JavaScript function to check the value in the textbox and validate.
<script language="javascript" type="text/javascript">
function ValidateGT20Function(source, arguments)
{
var val =
document.getElementById(document.getElementById(
source.id).getAttribute("controltovalidate")).value;
if (isNaN(val))
{
document.getElementById(source.id).setAttribute("errormessage",
"* number required");
arguments.IsValid = false;
}
else
{
if (document.getElementById("CheckBox1").getAttribute(
"Checked") == true)
{
if (val < 20000)
{
document.getElementById(source.id).setAttribute(
"errormessage", "* >20000 required");
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
}
else
{
if (val < 0)
{
document.getElementById(source.id).setAttribute(
"errormessage", "* >0 and <20000 required ");
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
}
}
}
</script>
Points of Interest
Maybe there are other solutions out there, but I couldn't find any. Please send me the link to any other possible solutions. Happy programming!! And don't forget to have fun.
History
- 10 October, 2007 -- Original version posted
License
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here.