IntroductionA common usage of web pages is collect information from user, and store it in a back end database, what is important and common is to validate the user input data before server can process on it. Although this validation can happen at server side, but ideally to save the server resources, the validation of input should happen at client side , by which it can give user fasted feedback . If validation is done manually by writing code to handle, it can be a lengthy task. Especially because the models for client side are programming typically by JavaScript and server side programming by asp.net are quite different. So the solutions are Validation Controls. They can be declared on web form and then bound to any other input control. What all we can validate: ListBox, DropDownList, RadioButtonList, HtmlInputText, HtmlTextArea, and HtmlSelect. What we cannot validate: RadioButton or CheckBox controls Process of Validation: we can ideally use validation control to verify a page automatically when user try to click submit button. Every button has CauseValidation property, which can be set to True of False. If True: ASP.NET will ignore the validation controls. If False: ASP.NET will automatically validate the page when the User clicks the button. It does this by performing the validation for each control on the page. This is default. Who is the Base class of validation control?The validation control classes are found in the System.Web.UI.WebControls namespace and inherit From the BaseValidator class.So let us take each of validation control and programs them as per their offerings.Before this follow below steps to create a user input form, Step1: Create an ASP.NET Website and name is “ValidationControls”. Step2: Create a table and input control like below , 1) Name: RequiredFieldValidator Server Tag : <asp:RequiredFieldValidator> Purpose: Checks that the control it has to validate is not empty when the form is submitted. Select Required Filed Validator from Toolbox , and drag it to name textbox. <asp:TextBox runat="server" Width="200px" ID="Name" />
<asp:RequiredFieldValidator ID="ValidateName"
ControlToValidate="Name"
runat="server" ErrorMessage="Name is Required"
Display=Dynamic>
</asp:RequiredFieldValidator>This is preety straight , we can do same for other textboxes. 2) Name: Range Fields Validator Server Tag : <asp:RangeValidator> Description: Checks that the value of the associated control is within a specified range. The value and the range can be numerical— a date or a string. We can use this to allow user to input Date Off between specified datetime, say between 08/05/08-08/20/08. So let’s drag range Validator next to Date Off textbox. <asp:TextBox runat="server" Width="200px" ID="DayOff" />
<asp:RequiredFieldValidator runat="server" ID="ValidateDayOff" ControlToValidate="DayOff" ErrorMessage="Day Off is required"
Display="dynamic">*
</asp:RequiredFieldValidator>
<asp:RangeValidator ID="ValidatedateOff2"
ControlToValidate="ValidateDayOff"
ErrorMessage="Date off is not within the valid interval"
MinimumValue="08/05/2008"
MaximumValue="08/20/2008"
SetFocusOnError="true"
Display="Dynamic"
runat="server"
></asp:RangeValidator>3) Name : CompareValidator Server Tag: <asp:CompareValidator> Description: Checks that the value of the associated control matches a specified comparison (less than, greater than, and and so on) against another constant value or control. Using this validator we can ask user to input age more than 18, i.e. > 18 <asp:TextBox runat="server" Width="200px" ID="Age" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Age" ErrorMessage="Age is required" Display="dynamic"
ID="Requiredfieldvalidator1">*
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator2" runat="server"
ControlToValidate="Age"
ValueToCompare="18"
Operator="GreaterThanEqual"
ErrorMessage="You must be at least 18-year-old"
Display=Dynamic
Type=Integer>
</asp:CompareValidator>You notice here we have many operators to use, we have used GreaterThan Equal; Similarly , we can assign Type of value with which we are comparing. Same we can do for re-password to compare with password, which should match it. <asp:TextBox runat="server" TextMode="Password" Width="200px" ID="Password2" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Password2" ErrorMessage="Password2 is required" Display="dynamic"
ID="Requiredfieldvalidator4"
Name="Requiredfieldvalidator4">
<img src="imgError.gif" alt="Missing required field." />
</asp:RequiredFieldValidator>
<asp:CompareValidator runat="server"
ControlToValidate="Password2"
ControlToCompare="Password"
Type="String"
ErrorMessage="The passwords don't match"
Display="dynamic"
ID="Comparevalidator1"
Name="Comparevalidator1">
<img src="imgError.gif" alt="Fields don't match." />
</asp:CompareValidator> You can notice here that we have set ControlToValidate= “Password2” And have used ControlToCompare = “Password” 4) Name: RegularExpressionValidator Server Tag : <asp:RegularExpressionValidator> Description: Checks if the value of the control it has to validate matches the specified regular expression. They allow you to specify complex rules that specify the characters, and in what sequence (position and number of occurrences) they are allowed, in the string. For example, the following control checks that the text input in the text box is a valid e-mail address: So here we will try to validate the email textbox, using regular expression validator <asp:TextBox runat="server" Width="200px" ID="Email" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Email" ErrorMessage="E-mail is required" Display="dynamic"
ID="Requiredfieldvalidator2">*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server"
ID="ValidateEmail"
ControlToValidate="Email"
validationExpression=".*@.{2,}\..{2,}"
ErrorMessage="E-mail is not in a valid format"
Display="dynamic">*
</asp:RegularExpressionValidator>Now here we have to concetrate on our validation expression : =".*@.{2,}\..{2,} The expression .*@.{2,}\..{2,} specifies that the string that it’s validating must begin with a number of characters (.*) and must contain an @ character, at least two more characters (the domain name), a period (escaped as \.), and, finally, at least two more characters for the domain extension. But yes Regular expression do not validate domain name
Let us try to invest more time here, we can also design more complex expression In addition to single characters, we can specify a class or a range of characters that can be matched in the expression. can specify that a certain character or class of characters must be present at least once, or between two and six times, and so on. Consider this expression
[aeiou]{2,4}\+[1-5]*Explanation: string should start with two to four vowels, have a + sign, and terminate with zero or more digits between 1 and 5. 5) Name: CustomValidator Server Tag : <asp:CustomValidator> Description: Allows you to specify any client-side JavaScript validation routine and its server- side counterpart to perform your own custom validation logic. CustomValidator allows you to execute your custom client-side and server-side validation routines. The client- side and server-side validation routines for the CustomValidator are declared similarly. They both take two parameters: a reference to the validator and a custom argument object Lets say we want to validate textbox ID to be multiple of 5, so for this we will create our own custom validator , one at client and other at server side. <asp:TextBox runat="server" Width="200px" ID="EmpID" />
<asp:RequiredFieldValidator runat="server" ID="ValidateEmpID" ControlToValidate="EmpID" ErrorMessage="ID is required"
Display="dynamic">*
</asp:RequiredFieldValidator>
<asp:CustomValidator runat="server" ID="ValidateEmpID2"
ControlToValidate="EmpID" ClientValidationFunction="EmpIDClientValidate"
ErrorMessage="ID must be a multiple of 5"
Display="dynamic" OnServerValidate="ValidateEmpID2_ServerValidate">*
</asp:CustomValidator>The client side javascript function is as below; <script type="text/javascript">
function EmpIDClientValidate(ctl, args)
{
// the value is a multiple of 5 if the module by 5 is 0
args.IsValid=(args.Value%5 == 0);
}
</script>And , the server side validation handler is as below; protected void ValidateEmpID2_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
args.IsValid = (int.Parse(args.Value) % 5 == 0);
}
catch
{
args.IsValid = false;
}
}6) Name : ValidationSummary Server tag: <asp:ValidationSummary> Description: Shows a summary with the error messages for each failed validator on the page (or in a pop-up message box). This actually doesn’t perform any validation. The summary display error message for each failed validation for validator controls. <asp:ValidationSummary runat="server"
ID="Summary"
DisplayMode="BulletList"
HeaderText="<b>Please review the following errors:</b>"
ShowSummary="true" />That all here, so finally we can write code for Submit Button click, protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)//If everything is fine.
Result.Text = "Thanks for sending your data";
else
Result.Text = "There are some errors, please correct them and re-send the form.";
}Download Sample ProjectDownload source files -129 kb SummaryIn this article, I have explained how to use validation controls in ASP.NET 3.5. hope help and thank you for reading. |