Friday 5 April 2013

Validation controls in ASP.Net:


Validation controls in ASP.Net:
ASP.Net validation controls checks the user input data to make sure that useless, unauthenticated or contradictory data don.t get stored.
ASP.Net gives the following validation controls:
1.     RequiredFieldValidator
2.     RangeValidator
3.     CompareValidator
4.     RegularExpressionValidator
5.     CustomValidator
6.     ValidationSummary
The BaseValidator Class:
The validation control classes inherit from the BaseValidator class and inherit its properties and functions. Therefore, it could help to take a look at the properties and the functions of this base class, which are common for all the validation controls:
Members
Description
ControlToValidateShows the input control to validate.
DisplayShows how the error message is shown.
EnableClientScriptShows whether client side validation will take.
EnabledActives or disables the validator.
ErrorMessageError string.
TextError text to be given if validation fails.
IsValidShows whether the value of the control is valid.
SetFocusOnErrorIt shows whether in case of an invalid control, the focus should switch to the related input control.
ValidationGroupThe logical group of multiple validators, where this control belongs.
Validate()This function revalidates the control and updates the IsValid property.
The RequiredFieldValidator:
The RequiredFieldValidator control makes sure that the needed field is not empty. It is usually tied to a text box to force input into the text box.
The syntax for the control:
<asp:RequiredFieldValidator ID="rfvcandidate"
        runat="server" ControlToValidate ="ddlcandidate"
        ErrorMessage="Please choose a candidate"
        InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
The RangeValidator:
The RangeValidator control checks that the input value falls within a predetermined range.
It has three specific properties:
Properties
Description
Typeit describes the type of the data; the available values are: Currency, Date, Double, String and Integer
 MinimumValueit denotes the minimum value of the range
MaximumValueit denotes the maximum value of the range
The syntax for the control:
<asp:RangeValidator ID="rvclass"
       runat="server"
       ControlToValidate="txtclass"
       ErrorMessage="Enter your class (6 - 12)"
       MaximumValue="12"
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>
The CompareValidator:
The CompareValidator control compares a value in one control with a value, or, a value in other control.
It has the subsequent specific properties:
Properties
Description
Typeit denotes the data type
ControlToCompareit denotes the value of the input control to compare with
ValueToCompareit denotes the constant value to compare with
Operatorit denotes the comparison operator, the available values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual and DataTypeCheck
The basic syntax for the control:
<asp:CompareValidator ID="CompareValidator1"
        runat="server"
        ErrorMessage="CompareValidator">
</asp:CompareValidator>
The RegularExpressionValidator
The RegularExpressionValidator gives validating the input text by matching against a pattern against a regular expression. The regular expression is fixed in the ValidationExpression property.
The following table summarizes the usually used syntax constructs for regular expressions:
Character Escapes
Description
\bequivalents a backspace
\tEquivalents a tab
\rEquivalents a carriage return
\vEquivalents a vertical tab
\fEquivalents a form feed
\nEquivalents a new line
\Escape character
Apart from single character match, a class of characters could be denoted that can be matched, called the metacharacters.
Metacharacters
Description
.Equivalents any character except \n
[abcd]Equivalents any character in the set
[^abcd]Excludes any character in the set
[2-7a-mA-M]Equivalents any character denoted in the range
\wEquivalents any alphanumeric character and underscore
\WEquivalents any non-word character
\sEquivalents whitespace characters like, space, tab, new line etc.
\SEquivalents any non-whitespace character
\dEquivalents any decimal character
\DEquivalents any non-decimal character
Quantifiers could be added to specify number of times a character could appear
Quantifier
Description
*Zero or more equivalents
+One or more equivalents
?Zero or one equivalents
{N}N equivalents
{N,}N or more equivalents
{N,M}Between N and M equivalents
The syntax for the control:
<asp:RegularExpressionValidator ID="string"
        runat="server"
        ErrorMessage="string"
        ValidationExpression="string"
        ValidationGroup="string">
</asp:RegularExpressionValidator>
The CustomValidator:
The CustomValidator control gives writing application related custom validation routines for both the client side and the server side validation.
The client side validation is completed through the ClientValidationFunction property. The client side validation routine could be written in a scripting language, like JavaScript or VBScript, which the browser may understand.
The server side validation routine has to be called from the control.s ServerValidate event handler. The server side validation routine could be written in any .Net language, like C# or VB.Net.
The basic syntax for the control
<asp:CustomValidator ID="CustomValidator1"
       runat="server"
       ClientValidationFunction=.cvf_func.
       ErrorMessage="CustomValidator">
</asp:CustomValidator>
The ValidationSummary Control
The ValidationSummary control does not operate any validation but indicates a summary of all errors in the page. The summary shows the values of the ErrorMessage property of all validation controls that failed validation.
The subsequent two mutually inclusive properties list out the error message:
  • ShowSummary: shows the error messages in denoted format.
  • ShowMessageBox: shows the error messages in a separate window.
The syntax for the control:
<asp:ValidationSummary ID="ValidationSummary1"
       runat="server"
       DisplayMode = "BulletList"
       ShowSummary = "true"
       HeaderText="Errors:" />
Validation Groups:
Complex pages have different groups of information given in different panels. In such a situation a require for performing validation separately for separate group, might arise. This type of situation is occurred using validation groups.
To organize a validation group, you could put the input controls and the validation controls into the similar logical group by setting their ValidationGroup property.
Example:
The following example explains a form to be filled up by all the students of a school, separated into four houses, for electing the school president. We will be using the validation controls to authenticate the user input.
The form in Design view:
343_validation control.png
The content file code:
<form id="form1" runat="server">
<table style="width: 66%;">
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
           Text="President Election Form : Choose your president"
           runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server" Width="239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
       runat="server" ControlToValidate ="ddlcandidate"
       ErrorMessage="Please choose a candidate"
       InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse"
      runat="server"
      RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse"
       runat="server"
       ControlToValidate="rblhouse"
       ErrorMessage="Enter your house name">
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass"
       runat="server" ControlToValidate="txtclass"
       ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" Width="250px">
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail"
      runat="server"
      ControlToValidate="txtemail" ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" Width="140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1"
      runat="server"
      DisplayMode ="BulletList"
      ShowSummary ="true"
      HeaderText="Errors:" />
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
   if (Page.IsValid)
   {
      lblmsg.Text = "Thank You";
   }
   else
   {
      lblmsg.Text = "Fill up all the fields";
   }
}

No comments:

Post a Comment