Validation Controls in ASP.Net

By
Advertisement
It's very important to validate the user input in any data entry forms. Improper validation of form data is one of the main causes of security vulnerabilities. Invalid data can cause unexpected errors in system and also It exposes your website to attacks such as cross-site scripting and SQL injections etc. ASP.NET is rich with validation controls and In this article I’m trying to explore the ASP.NET Validation controls in depth with the help of samples.  I hope you will enjoy this article.
For your reference I have attached the source code(s) for all the sections with this article. 
I have put my time and efforts on all of my articles, Please don't forget to mark your votessuggestions and feedbackto improve the quality of this and upcoming articles.   
If we are assuming that the user will enter all data in expected form then it’s a wrong assumption. It’s always better to validate the user input before accepting to the system. For an example if we are expecting a number input from the user, then allow only numbers in that data entry control to avoid unexpected behavior of the system. The amount of validation you put in a program depends on how complex the system is. ASP.NET Validation controls can be used for Server-side and Client-side validations.  
We can validate the user input from client-side and or server-side, if we just wanted to validate the user input only in client-side then we can use JavaScript or any other scripting languages.  It's always advised to to do validations in server side also. 
We can easily validate the user input by using ASP.NET validation controls. It provides an easy to use mechanism for all common types of standard validation. This validation controls can be used with HTML and Web Server controls. Six validation controls are available with ASP.NET as of now, they are as follows. 
The RequiredFieldValidator Control - Ensures that the user does not skip a mandatory entry field . 

The CompareValidator Control – Compares one controls value with another controls value, constants and data type using a comparison operator (equals, greater than, less than, and so on). 

The RangeValidator Control - Checks the user's input is in a given range (eg: numbers or characters). 

The RegularExpressionValidator Control - Checks that the user's entry matches a pattern defined by a regular expression.  

The CustomValidator Control - Checks the user's entry using custom-coded validation logic. 

The ValidationSummary Control - Displays a summary of all validation errors inline on a web page, in a message box, or both. 
All validation controls except ValidationSummary are used to validate the user input, whereas theValidationSummary control is just used to display the entire validation error messages in a particular area. This error list can be printed in the browser and or displayed as a dialogue box. The CustomValidator allows you to implement your own validations. By using CustomValidator you can perform complex validations or you can validate the data from the database etc.
I have explained all the Validation Controls in the section - Validation Controls in depth.  
If you look at the hierarchy you can see that there is one another validation control derived from BaseValidator class.  
The Dynamic Validator Control - The DynamicValidator control is part of the ASP.NET Dynamic Data framework. The control catches exceptions that are thrown from the data model during validation and raises the exception as a validation event on the Web page.     
This control can be found in the Dynamic Data section of the Toolbox .
This control was added in .NET Framework 3.5 SP1 release. The DynamicValidator control can be used with data fields or data entities. It catches exceptions that are thrown in LINQ-to-SQL classes or entity in extensibility methods in the data model. The DynamicValidator control is associated with the controls that accept user input.  
By default, ASP.NET Dynamic Data does not display all exceptions from the data model in the page, because some database exceptions might contain confidential information. Dynamic Data displays ValidationException values only. If you want your application to display other exceptions, you can create a DynamicValidator control, provide the exceptions that you want to display, and attach the exceptions to the DynamicValidator control. The exceptions that are thrown in the data model will be displayed in all pages in the application.  
All controls that can be validated have a ValidationPropertyAttribute attribute , which indicates which property should be read for the purposes of validation. For validation to work client-side as well, this property must correspond to the value attribute of the HTML element that gets rendered on the client Also, a control must have a single logical value on the client. This is why RadioButtonList can be validated, but CheckBoxList cannot. 
If you are creating a validatable UserControl then the System.Web.UI.ValidationPropertyAttributeattribute must be applied to that control, example. 
 [ValidationPropertyAttribute("Message")]
public class MessageControl : Label
{
   private int _message = 0;
   public int Message
   {
      get
      {
         return _message;
      }
      set
      {
         _message = value;
      }
   }
}
All validation controls except ValidationSummary are derived from BaseValidator class and share some properties.   

If you look at the above image you can see that CompareValidator and RangeValidator are derived from the BaseCompareValidator class. This class offers two main common property in addition to those offered byBaseValidatorClass.
I have explained all these properties in the next section.
ValidationSummary is derived directly from WebControl class and this control is used only for reporting all the validation error messages to the end user.
The below given properties are common for the Validation Controls that are derived from BaseValidator Class. 

Apart from standard Font and other Formatting properties, the controls derived from BaseValidator class have the following properties in common. 
ControlToValidate – ID of the control which we are going to validate. The control must be developed usingValidatioPropertyAttribute. So if you develop any user control that may require validation then add this attribute to your control class. Read More on ValidatioPropertyAttribute from MSDN.    
Display – Display behavior of the error message in validation control, possible values are “None”, “Static”, ”Dynamic”. This property is explained in coming section
None - The validation message is never displayed. 
Static - The control displays an error message if validation fails. Space for the validation message is allocated in the layout of the page even if the input passes validation.  
Dynamic - The control displays an error message if validation fails. Space for the validation message is dynamically added to the page if validation fails. (If client-side validation is not active Static and Dynamicbehave the same way). 
EnableClientScript – Use this property to enable or disable client-side validation. 

Enabled – Use this property to enable or disable the validation control. If this property is set to false then it will prevent validation being performed. 

ErrorMessage – Error message displayed in a ValidationSummary control when validation fails. 
Text – Error Message displayed in the validation control when validation fails. I have given another section on Difference between Text and ErrorMessage property
SetFocusOnError – Boolean value used to set focus to the control mentioned in the ControlToValidatewhen validation fails. 
ValidationGroup – The name of the validation group to which this validation control belongs, Detailed explanation is given in another section
IsValid – Boolean value that indicates the validation status.  
The BaseCompareValidator offers two main property in common in addition to those offered by theBaseValidator class.  
CultureInvariantValues - Boolean value indicating whether values are converted to a culture-neutral format before being compared.  

Type - Validation fails if the value cannot be converted to the specified data type, Possible values for Type are StringIntegerDoubleDateCurrency.    
Note: Consider the culture of the web application while doing any comparison, especially when doing Date, Currency comparison.
The main method that’s common for all controls derived from BaseValidator class is Validate().  
Validate - Performs validation on the associated input control and updates the IsValid property, Detailed explanation is given in another section.
ASP.NET Validation Controls provides Client-side validation and Server-side validation. We can enable or disable the Client-side validation by setting a true/false value to the EnableClientScript property of the Validation Control. We don’t need to do anything special for Client-Side validation except setting the property EnableClientScript=true. By enabling Client-side validation we can reduce the round trips. 
If Client-side validation is enabled, the page includes references to script libraries that are used to perform the client-side validation. Every validation control makes sure that a standard block of client script is emitted into the page. This is actually just a small amount of script that includes a reference to code in a script library called WebUIValidation.js. Client-side validation uses the same error display mechanism as server-side validation. The Validation Controls automatically detects the client’s browser is enabled for client-side script validation. If it’s disabled then, client side validations are bypassed and validations are performed only on the web server. 
If you want to forcefully disable client-side validation and perform only server-side validation for the page then set the page attribute ClientTarget to DownLevel 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<%@ Page ClientTarget="DownLevel" %>  
Whereas setting the page attribute ClientTarget to UpLevel will force the controls to do both validations.  

<%@ Page ClientTarget="UpLevel" %> 
It’s better to leave this to Validation Controls instead of setting this attribute for forcefully enabling or disabling the validations on the page.    
CausesValidation and ValidationGroup are the validation control related properties associated with some of the web server controls. I have explained the usage in an another section.

CausesValidation - Boolean value indicating whether the control causes validation to be performed on any controls that require validation when it receives focus. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done. By default CausesValidation is set to true. 
This property is available to the ButtonImageButton, and LinkButton Web server controls, theHtmlInputButtonHtmlInputImage, and HtmlButton HTML server controls, and controls that can automatically post back to the server such as the TextBoxCheckBoxListControl, and BulletedList controls. 
ValidationGroup - The group of controls for which the server control causes validation when it posts back to the server  
There are two properties and one method associated with page class related to validation controls, they are listed below. I have given an example for this in another section 

IsValid - Gets a value indicating whether page validation succeeded.  
Validators - This property will return a collection of validation controls in the page 
Validate method is the main method that will be used for validating the validation controls from server side. 

Validate - Validating the All Validation Controls with in the page   
Validate(String) - Validating Validation Controls for a specified validation group  
ASP.NET validation controls provide functionality to perform validation using client script. When client-side validation is being performed, the user cannot post the page to the server if there are errors on the page thus reducing round-trips. The following properties are available in client-side.  
Page_IsValid - It's client side value used to identify the page is error free from the client side itself.   
Page_Validators - This property will return the collection of validation controls in the page. 
Page_ValidationActive - Indicates whether validation should take place. Set this variable to False to turn off validation programmatically.  
Isvalid -  Boolean value returns the associated validation control's validation failed or succeed. 
The following functions can be called from client-side for validation purpose. 

ValidatorValidate(val) - Takes a client-validator as input. Makes the validator check its input and update its display.  
ValidatorEnable(val, enable) - Enables or disables a client validator. Here "val" is the validation control and "enable" is the Boolean value. An example given in the section Conditional Validation  
ValidatorHookupControl(control, val) - Takes an input HTML element and a client-validator. Modifies or creates the element's change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values. 
Page_ClientValidate - Client-side function to validate all the Validation Controls with in the page  
Page_ClientValidate(ValGroup) -  Client-side function to validate all the Validation Controls with in the page  with the specified ValidationGroup. 
Here I will give a detailed description of all validation controls with examples. All working codes are attached with this article, you may download the relevant files for your reference. 

This is the simplest and most used control from validation control series. This control makes sure that the required field is entered by the user. For making a control mandatory we just need to tie a RequiredFieldValidator to that control. Leading and trailing spaces of the input value are removed before validation.
The only one property unique to this validation control is InitialValue.
InitialValue - This property can be used to mention the controls default value that needs to be changed with another value. RequiredFieldValidator ensures that the controls value is filled and not the initial value. 
Note: The InitialValue property does not set the default value for the input control. It indicates the value that you do not want the user to enter in the input control.
Read More... 
I will try to explain this control with the help of a sample. 
HTML
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server"
                ControlToValidate="txtEmail" ForeColor="Red"
                ToolTip="Please enter your email" Display="Dynamic">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Phone
        </td>
        <td>
            <asp:TextBox ID="txtPhone" runat="server" Width="140px"></asp:TextBox>
            <br />
            <asp:RequiredFieldValidator ID="rfvPjone" runat="server"
                ControlToValidate="txtPhone" ForeColor="Red"
                Text="Please enter your phone no" Display="Dynamic"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Profession
        </td>
        <td>
            <asp:DropDownList ID="drpProfession" runat="server" Width="140px">
                <asp:ListItem Selected="True">-Select-</asp:ListItem>
                <asp:ListItem>Writer</asp:ListItem>
                <asp:ListItem>Editor</asp:ListItem>
                <asp:ListItem>Engineer</asp:ListItem>
                <asp:ListItem>Cashier</asp:ListItem>
            </asp:DropDownList>
            <br />
            <asp:RequiredFieldValidator ID="rfvProfession" runat="server"
                ErrorMessage="Please select your profession"
                ForeColor="Red" ControlToValidate="drpProfession"
                InitialValue="-Select-" Display="Dynamic"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Phone
        </td>
        <td>
            <asp:Label ID="lblPhone" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Profession
        </td>
        <td>
            <asp:Label ID="lblProfession" runat="server"></asp:Label>
        </td>
    </tr>
</table>
RequiredFieldValidator is used to make a field mandatory. Here I have three controls for capturing, Email, Phone, Profession. All fields are mandatory. to make the fields mandatory I have added RequiredFieldValidator for all the controls and mentioned the control name in the ControlToValidate property. 
To handle the default value in drop-down  I have specified the InitialValue of the Validation control to "-Select-". To succeed the validation we need to make sure that the control is having some other value than the value mentioned in InitialValue
Code-Behind 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
    lblPhone.Text = txtPhone.Text;
    lblProfession.Text = drpProfession.SelectedItem.Text;
In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side 
This control is used to compare the value entered in one control with another value (another control’s value, a database value, any specified Data Type value, any other value that you specify).
Note: If the input control value is empty then no validation will take place and will return IsValid true for this validator. If it's a mandatory field then add a RequiredFieldValidator also to that input control.  
The unique properties that offered by this control in addition to the properties of BaseValidator andBaseCompareValidator are Operator and ValueToCompare. 
ValueToCompare - The constant value to compare with the value entered by the user into the input control being validated. The default value is String.Empty.  
Note: Do not set both the ControlToCompare and ValueToCompare properties at the same time. You can either compare the value of an input control to another input control, or to a constant value. If both properties are set, the ControlToCompare property takes precedence.  
Operator - Use this property to specify the comparison operation to perform. The following are the comparison operations that are possible.  
Equal  - A comparison for equality between the values of the input control being validated and another control, or a constant value.
NotEqual - A comparison for inequality between the values of the input control being validated and another control, or a constant value.
GreaterThan - A comparison for greater than between the values of the input control being validated and another control, or a constant value.
GreaterThanEqual - A comparison for greater than or equal to between the values of the input control being validated and another control, or a constant value.
LessThan - A comparison for less than between the values of the input control being validated and another control, or a constant value. 
LessThanEqual - A comparison for less than or equal to between the values of the input control being validated and another control, or a constant value.
DataTypeCheck - A data type comparison of the value entered in the input control being validated and the data type specified by the BaseCompareValidator.Type property. Validation fails if the value cannot be converted to the specified data type.
Note: The ControlToCompare and ValueToCompare properties are ignored when 'DataTypeCheck' operator is used.  
Below is an example that will explain CompareValidator in detail.
HTML  
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server"
            ControlToValidate="txtEmail" ForeColor="Red"
            ToolTip="Please enter your email" Display="Dynamic">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Confirm Email
        </td>
        <td>
            <asp:TextBox ID="txtConfirmEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvConfirmEmail" runat="server" ControlToValidate="txtConfirmEmail"
                ForeColor="Red" ToolTip="Please confirm your email">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvConfirmEmail" runat="server" ErrorMessage="Email do not match!"
                ControlToValidate="txtConfirmEmail" ControlToCompare="txtEmail"
                Display="Dynamic" ForeColor="Red"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Age
        </td>
        <td>
            <asp:TextBox ID="txtAge" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvAge" runat="server" ControlToValidate="txtAge"
                ForeColor="Red" ToolTip="Please enter your age" Display="Dynamic">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvAge" runat="server" ErrorMessage="Please enter a number"
                ForeColor="Red" ControlToValidate="txtAge" Type="Integer"
                Operator="DataTypeCheck" Display="Dynamic"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:TextBox ID="txtExperience" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <br />
            <asp:CompareValidator ID="cvExperience" runat="server"
                ErrorMessage="You must have 5 Year Exp or above to apply"
                Operator="GreaterThanEqual" ValueToCompare="5" ControlToValidate="txtExperience"
                Type="Integer" Display="Dynamic" ForeColor="Red"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Age
        </td>
        <td>
            <asp:Label ID="lblAge" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:Label ID="lblExperience" runat="server"></asp:Label>
        </td>
    </tr>
</table>
CompareValidator is used to compare the control's value with any other value,that can be value of any other control , datatype, constant value. If you see here I have used multiple validation controls together, the reason is that the CompareValidator does not check for mandatory field thats why I have added aRequiredFieldValidator control. I have explained multiple validations in another section. 
Here I have written code for comparing two emails, age needs to be an integer value and experience needs to be greater than 5 Years. The corresponding validation controls TypeValueToCompareControlToCompareOperatoretc properties are assigned accordingly.  
Code-Behind 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
    lblAge.Text = txtAge.Text;
    lblExperience.Text = txtExperience.Text + " Years";
}  
In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side. 
The RangeValidator server control is similar to the CompareValidator server control, This control is used to check that the user enters an input value that falls between two values. It is possible to check ranges within numbers, dates, and characters.
Note: If the input control value is empty then no validation will take place and will return IsValid true for this validator. If it's a required field then add a RequiredFieldValidator also.   
The unique properties that offered by this control in addition to the properties of BaseValidator andBaseCompareValidator are MinimumValue and MaximumValue
MaximumValue - Use this property to specify the maximum value of the validation range.
MinimumValue - Use this property to specify the minimum value of the validation range 
Read More...  
Sample:
HTML 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Experience
        </td>
        <td>
            <asp:TextBox ID="txtExperience" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvExperience" runat="server" ControlToValidate="txtExperience"
                ForeColor="Red" ToolTip="Please enter your experience" Display="Dynamic">*</asp:RequiredFieldValidator>
            <br />
            <asp:RangeValidator ID="rvExperience" runat="server" ControlToValidate="txtExperience"
                Type="Integer" ErrorMessage="You must have 5 to 15 Years of Exp to apply" MaximumValue="15"
                MinimumValue="5" Display="Dynamic" ForeColor="Red"></asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Grade
        </td>
        <td>
            <asp:DropDownList ID="drpGrade" runat="server" Width="140px">
                <asp:ListItem Selected="True">-Select-</asp:ListItem>
                <asp:ListItem>A</asp:ListItem>
                <asp:ListItem>B</asp:ListItem>
                <asp:ListItem>C</asp:ListItem>
                <asp:ListItem>D</asp:ListItem>
                <asp:ListItem>E</asp:ListItem>
            </asp:DropDownList>
            <br />
            <asp:RangeValidator ID="rvGrade" runat="server" ControlToValidate="drpGrade"
            ErrorMessage="Your accademic grade needs to be between A and C to apply"
                MaximumValue="C" MinimumValue="A" Display="Dynamic"  ForeColor="Red"></asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:Label ID="lblExperience" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Grade
        </td>
        <td>
            <asp:Label ID="lblGrade" runat="server"></asp:Label>
        </td>
    </tr>
</table>
RangeValidator ensures that the control's value is in a given range. In this example the criteria is, Experience needs to be with 5 years to 15 years and grade needs to be between A & B. The validation controls values MinimumValueand MaximumValues are assigned accordingly. 
Code-Behind 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void btnSave_Click(object sender, EventArgs e)
{
    lblExperience.Text = txtExperience.Text + " Years";
    lblGrade.Text = drpGrade.Text;
}
In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side.
This control check the user's input based on a pattern defined by a regular expression. This validation control is very helpful when checking email address, phone number, zip code etc, Usually in the previous time we used to do considerably big functions for this kind of validations. 
Note: The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field as required.
A great place on the Internet to find free regular expressions is the RegEx Library
The only one unique property that offered by this control in addition to the properties of BaseValidator isValidationExpression
ValidationExpression - A string that specifies the regular expression used to validate a field for format. 
The following example demonstrates the usage of RegularExpressionValidator. 
HTML
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <br />
            <asp:RegularExpressionValidator
                ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
                ForeColor="Red" Display="Dynamic" ErrorMessage="Please enter a valid email address"
                ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
</table>
Here The RegularExpressionValidator is used to validate an email Id and the validation pattern is given in the ValidationExpression property. 
Code-Behind
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
}
In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side

The CustomValidator Control 
The CustomValidator server control enables you to develop your own custom server-side or client-side validations. At times, you may want to compare the user's input to a value in a database, or to determine whether his input conforms to some arithmetic validation that you are looking for. You can do all this and more by using this type of validation control.
Two unique properties and one unique event handler are associated with CustomValidator. They are,
Description: http://www.codeproject.com/KB/aspnet/426761/p.gifClientValidationFunction - Name of the custom client-side script function used for validation.  
Note: The script must be in a language that the browser supports, such as VBScript or JScript.    
ValidateEmptyText - Boolean value indicating whether empty text should be validated. setting this property to false will cause the validation control to bypass the validation in-case of empty string .  
OnServerValidate - Specifies the name of the server-side validation script function to be executed.  
We can understand these properties with the help of a sample.
JavaScript
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
function clientValidateUserName(sender, args) {
    args.IsValid = false;
    var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
    if (!reg.test(args.Value)) {
        args.IsValid = true;
    }
}
The above JavaScript will be called in client-side by the CustomValidator. This function checks the entered value.If it's an integer value then it will set the IsValid property to false and thus custom validator's validation will get failed in client side. If it's succeeded then it will send to the server-side validation method "serverValidateUserName".  
HTML 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            User
        </td>
        <td>
            <asp:TextBox ID="txtUserName" runat="server" Width="140px"></asp:TextBox>
            <br />
            <asp:CustomValidator ID="customVUserName" runat="server" ControlToValidate="txtUserName"
                Display="Dynamic" ErrorMessage="*" ClientValidationFunction="clientValidateUserName"
                OnServerValidate="serverValidateUserName"
                Text="The User Name you entered is incorrect or not an admin."
                ValidateEmptyText="true" ForeColor="Red" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
                User
        </td>
        <td>
            <asp:Label ID="lblUserName" runat="server"></asp:Label>
        </td>
    </tr>
</table>
Here the JavaScript function that we defined mentioned before is assigned in ClientValidationFunctionproperty and the server-side handler (method) is assigned in  OnServerValidate property. 
Code-Behind 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void btnLogin_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblUserName.Text = txtUserName.Text + " is a valid admin user";
    }
    else
    {
        lblUserName.Text = txtUserName.Text + " is not a valid admin user";
    }
}
protected void serverValidateUserName(object sender, ServerValidateEventArgs args)
{
    args.IsValid = false;
    if (!string.IsNullOrEmpty(args.Value))
    {
        args.IsValid = AvailableAdmins.Contains(args.Value);
    }
}
public string[] AvailableAdmins { get { return new string[] { "Shemeer", "Aydin", "Dave" }; } }
In "serverValidateUserName" method it's checking the entered user name is available in the predefined list, If not it the validation will fail otherwise validation will get succeeded.  
The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property.
The error message displayed in this control is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed for that validation control.
The unique properties that offered by ValidationSummary control are follows,
DisplayMode - Use this property to specify the display format of a ValidationSummary control. The summary can be displayed as a list, as a bulleted list, or as a single paragraph.The default is BulletList.  
List - Validation summary displayed in a list.
BulletList - Validation summary displayed in a bulleted list.
SingleParagraph - Validation summary displayed in a single paragraph. 
HeaderText - The header text displayed at the top of the summary.
ShowMessageBox - A Boolean value that specifies whether the summary should be displayed in a message box or not. 
ShowSummary - A Boolean value that specifies whether the ValidationSummary control should be displayed or hidden. 
Below given example demonstrates how to use a ValidationSummary control to summarize the error messages from all validation controls on a Web page and display them in a bulleted list with a HeaderText.
HTML 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmail"
                ForeColor="Red" ToolTip="Please enter your email" Display="Dynamic"
                ErrorMessage="Please enter your email">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Age
        </td>
        <td>
            <asp:TextBox ID="txtAge" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvAge" runat="server" ControlToValidate="txtAge"
                ForeColor="Red" ToolTip="Please enter your age" Display="Dynamic"
                ErrorMessage="Please enter your age">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvAge" runat="server" ErrorMessage="Please enter a number"
                ForeColor="Red" ControlToValidate="txtAge" Type="Integer" Operator="DataTypeCheck"
                Display="Dynamic"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:TextBox ID="txtExperience" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <br />
            <asp:CompareValidator ID="cvExperience" runat="server"
            ErrorMessage="You must have 5 Year Exp or above to apply"
                Operator="GreaterThanEqual" ValueToCompare="5"
                ControlToValidate="txtExperience"
                Type="Integer" Display="Dynamic" ForeColor="Red"
                ToolTip="You must have 5 Year Exp or above to apply">*</asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:ValidationSummary ID="vsSample" runat="server"
            DisplayMode="BulletList" ShowMessageBox="true"
                ShowSummary="true" ForeColor="Red"
                HeaderText="Correct the following errors." />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save"
            OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Age
        </td>
        <td>
            <asp:Label ID="lblAge" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:Label ID="lblExperience" runat="server"></asp:Label>
        </td>
    </tr>
</table>
Here by using ValidationSummary Control we are showing all the validation error messages in the browser and in alert message.
We have used the properties DisplayMode="BulletList"ShowMessageBox="true", ShowSummary="true", ForeColor="Red" and HeaderText="Correct the following errors." You can see the expected output in the output section. 
Code-Behind 
Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
    lblAge.Text = txtAge.Text;
    lblExperience.Text = txtExperience.Text + " Years";
}
In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side  

0 comments:

Post a Comment

Online Casino