Wednesday, 24 October 2012

ValidationControls |TextArea validation using RegularExpressionValidator |ValidationSummary using ValidationGroup Date Validation using RegularExpressionValidator



Asp.Net - using ValidationControls with ValidationSummary 

In Asp.Net we can use the Validation controls which come built in with Asp.net. Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

Now suppose we have multiple controls in a form, and each controls is associated with one or more validation controls, we will have to display the summary of all the validation in a single messagebox, to do so we can make use of the ValidationSummary control.

For example let us consider a textbox, which can accept only US Phone numbers, let us try to do the validation for this controls and associate the same with a ValidationSummary control.
Open an Asp.net page and add the control and the validationcontrol

<asp:TextBox
id="txtBusinessOwnerPhone"
runat="server"
CssClass="text"
MaxLength="12">
</asp:TextBox>
<asp:RegularExpressionValidator
ID="valtxtBusinessOwnerPhone"
runat="server"
ControlToValidate="txtBusinessOwnerPhone"
ValidationExpression="[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}[-]"
Display="None"
Text="*"
ErrorMessage="Enter Phone# in the format 999-999-9999">
</asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<
asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Phone number in the textbox and click on the Save button.



That's it, we have implemented the ValidationSummary control for the Asp.Net Validation controls.

2. Asp.Net - Date Validation using RegularExpressionValidator 


Date validation using Asp.Net RegularExpressionValidator
Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

To validate the date, we can use the RegularExpressionValidator. This validator requires a regular expression which will validate the pattern of data entered in the control.


Open an Asp.net page and add a TextBox control, also add a RegularExpressionValidator control to validate the date entered in the TextBox


<asp:TextBox ID="txtDate" runat="server">asp:TextBox>
<
asp:RegularExpressionValidator
ID="val txtDate "
runat="server"
ControlToValidate=" txtDate "
Display="None"
ErrorMessage="Enter a valid Date, Format (mm/dd/yyyy)"
SetFocusOnError="True"
ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$">
*asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<
asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Date in the textbox and click on the Save button.
You should get the Error message as follows.




3-Asp.Net - ValidationSummary using ValidationGroup 

In Asp.Net the ValidationSummary control consolidates the validation detials and error messages of all the validation controls in the page and provides a summary report of all the validation failures in the page.


Suppose we have a large page and we need to group the validations in the page based on specific groups, here we need to use the ValidationGroup property, the ValidationGroup property should be set to the controls which are part of the group, the ValidationSummary control and the button which will handle the submit/postback of this group.

Here’s the code below


<
asp:TextBox id="txtPhone" runat="server" CssClass="text" MaxLength="12">asp:TextBox>

<asp:RegularExpressionValidator ID="valtxtPhone" runat="server" ControlToValidate="txtPhone" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" Display="None" Text="*" ValidationGroup="valGroup" ErrorMessage="Enter Phone# in the format 999-999-9999" SetFocusOnError="true">asp:RegularExpressionValidator>

<asp:Button ID="cmdSave" runat="server" Text="Save" ValidationGroup="valGroup" />

<asp:ValidationSummary ID="valSummary" runat="server" DisplayMode="List" ValidationGroup="valGroup" ShowMessageBox="True" ShowSummary="False" EnableClientScript="true"/>

Now build and run the project, enter an invalid Phone# in the textbox and click on the Save button. You should get an error message.

Also notice that other validations in the page, which are not bound to this ValidationGroup will not get fired.

That's it, we have implemented the ValidationGroup in the ValidationSummary control for the Asp.Net Validation controls.


4-Asp.Net - TextArea validation using RegularExpressionValidator 

The Asp.Net TextArea control doesnot support the MaxLength property, though you set the MaxLength property, the TextArea control will not restrict the users to enter text within the set limit. The MaxLengh property works fine with the TextBox controls, but when it comes to TextArea controls (TextMode = MultiLine) the MaxLength property fails.

The RegularExpressionValidator, control can be used to validate the MaxLength property of the TextArea control. Her’s how this can be accomplished.

Add a TextBox control to your Asp.net form and set its TextMode property to MultiLine, then add a RegularExpressionValidator control with the regular expression to restrict the length of the text in the TextBox.

Here’s the code

<asp:TextBox id="txtProjectDescription"
 runat="server"
 CssClass="text"
 MaxLength="2500"
 Width="500px"
 TextMode="MultiLine"
 Rows="5">
asp:TextBox>

<asp:RegularExpressionValidator
ID="valtxtProjectDescription"
runat="server"
ControlToValidate="txtProjectDescription"
Display="None"
ErrorMessage="Project Description Should be less than 2500 Characters"
SetFocusOnError="True"
ValidationExpression="^([\S\s]{0,2500})$">
asp:RegularExpressionValidator>

Add the Save Button and the Validation Summery control
<asp:Button
ID="cmdSave"
runat="server"
Text="Save"
/>

<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter a text with length more that 2500 characters in the TextArea. You should get an error message 

Project Description Should be less than 2500 Characters


5-RangeValidator in Asp.Net 

The RangeValidator is used to make sure that the user enters a value within a pre-defined range of values, this validate is often used to validate numeric value inputs from the user.

The below code snipet adds a TextBox to an Asp.net form and associates an Asp.Net RangeValidator to the text box to make sure that the text box accepts only values in the range 1.. 1000

<asp:TextBox
ID="txtID"
runat="server"
MaxLength="25">
</asp:TextBox>

<asp:RangeValidator
ID="valtxtID "
runat="server"
ControlToValidate="txtID"
          Display="Dynamic"
ErrorMessage="Please enter a valid number (1..1000)."
MinimumValue="1"
MaximumValue="1000"
Type="Integer"
SetFocusOnError="True">*
</asp:RangeValidator>

The above RangeValidator makes sure that only numeric values in the range 1..1000 are entered in the txtID textbox, any other values will lead to an error message prompt.

The RangeValidator
 also takes care of the datatype of the value which is entered in the TextBox, the Type="Integer" property makes sure that only Integer values are entered into the TextBox.

Finally add a ValidationSummary control to consolidate all the validations in the page.



<asp:Button ID="cmdSave"
runat="server"
Text="Save"
OnClick="cmdSave_Click" />
              
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
      ShowSummary="False"
EnableClientScript="true" />
</asp:ValidationSummary>

Once we are done with the code in the .aspx page, we should also make sure that the validations are passed in the server side in the .vb/.cs code behind file.

Asp.Net performs the validations both in the client and the server side, of the users' browser doesn’t support JavaScript then the client side validation might get skipped, however the same validation in done by Asp.Net in the server side also. 

The
 Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.

if (Page.IsValid)
{
   //DB save and other server side logic goes here
}
 
That’s it we have seen, how to use the RangeValidator to validate user input in an Asp.net form.


6-RequiredFieldValidator in Asp.Net 

As the name implies, the RequiredFieldValidator is used to make sure that the user enter a value for a specific field in the form.

A RequiredFieldValidator can be associated with a control which cannot be empty while submitting the form.

The below code snipet adds a TextBox to an Asp.net form and associates an Asp.Net RequiredFieldValidator to the text box to make sure that the Name is entered before submitting the form.

<asp:TextBox
ID="txtName"
runat="server"
MaxLength="250">
</asp:TextBox>
                                                                <asp:RequiredFieldValidator
ID="valtxtName"
runat="server"
ControlToValidate="txtName"                                                                    Display="Dynamic"
ErrorMessage="Please enter Name."
SetFocusOnError="True">*
</asp:RequiredFieldValidator>

The RequiredFieldValidator also takes care of the white spaces in the TextBox, the validator makes sure that the user does not just type some white spaces and submit the form, it makes sure that a valid Character or Number is entered before submitting the form.

Finally add a ValidationSummary control to consolidate all the validations in the page.


<asp:Button ID="cmdSave"
runat="server"
Text="Save"
OnClick="cmdSave_Click" />
              
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
      ShowSummary="False"
</EnableClientScript="true" />

Once we are done with the code in the .aspx page, we should also make sure that the validations are passed in ther server side in the .vb/.cs code behind file.

Asp.Net performs the validations both in the client and the server side, of the users' browser doesn’t support JavaScript then the client side validation might get skipped, however the same validation in done by Asp.Net in the server side also.

The Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.

if (Page.IsValid)
{
   //DB save and other server side logic goes here
}
 

That’s it we have seen, how to use the RequiredFieldValidator to validate user input in an Asp.net form


7- Asp.net CustomValidator – JavaScript client side validation 

As the name implies, the CustomValidator is used to perform custom validations in an Asp.Net page, the CustomValidator is very handy when we need to perform complex validations involving more than one control in an Asp.net page.

CustomValidator can be associated with either a client side JavaScript function or with a server side VB.Net/C# function. In this post we shall see on how to use the CustomValidator for client side JavaScript validation.


The below code snippet adds a DropDownList and a TextBox control to an Asp.net form with an Asp.Net CustomValidator which validates the combination of values from both these controls.

Condition to validate: If others is selected in the drpCountry DropDownList, then the txtName TextBox should not be empty.

Select Country:
<asp:DropDownList ID="drpCountry" runat="server">
    <asp:ListItem>India</asp:ListItem>
    <asp:ListItem>USA</asp:ListItem>
    <asp:ListItem>UK</asp:ListItem>
    <asp:ListItem>Others</asp:ListItem>
</asp:DropDownList><br />

<asp:Label ID="lblText" runat="server" Text="If Others enter Country Name: " />
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Button ID="cmdSave" Text="Submit" runat="server"/>
    <br />
    <br />
<asp:CustomValidator
    ID="valCountry"
    ControlToValidate="drpCountry"
    ClientValidationFunction="validateCountry"
    Text="Please enter Country Name"
    runat="server"/>

The ClientValidationFunction property of the CustomValidator calls the JavaScript function validateCountry.

Here is the JavaScript function

<script type="text/javascript" language="javascript">

    function validateCountry(oSrc, args)
    {
        vSelection = document.getElementById("drpCountry");
        vName = document.getElementById("txtName");
        if(vSelection.value != "Others")
        {
            args.IsValid = true;
            return;
        }
        //   
        if (vName.value.length == 0)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
</script>


Now if you try to save the form by selecting Others in the drpCountry DropDownList with an empty value in the txtName TextBox then the validation fires and displays the message.

Please enter Country Name

That’s it we have seen the usage of a CustomValidator with JavaScript validation.

8-Asp.net CustomValidator - Server side validation 

As the name implies, the CustomValidator is used to perform custom validations in an Asp.Net page, the CustomValidator is very handy when we need to perform complex validations involving more than one control in an Asp.net page.

CustomValidator  can be associated with either a client side JavaScript function or with a server side VB.Net/C# function. In this post we shall see on how to use the CustomValidator for server side validation.


 
The below code snippet adds a DropDownList and a TextBox control to an Asp.net form with an Asp.Net CustomValidator which validates the combination of values from both these controls.

Condition to validate: If Others is selected in the drpCountry DropDownList, then the txtName TextBox should not be empty.

Select Country:
<asp:DropDownList ID="drpCountry" runat="server">
    <asp:ListItem>India</asp:ListItem>
    <asp:ListItem>USA</asp:ListItem>
    <asp:ListItem>UK</asp:ListItem>
    <asp:ListItem>Others</asp:ListItem>
</asp:DropDownList><br />

<asp:Label ID="lblText" runat="server" Text="If Others enter Country Name: " />
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Button ID="cmdSave" Text="Submit" runat="server"/>
    <br />
    <br />
<asp:CustomValidator
    ID="valCountry"
    ControlToValidate="drpCountry"
    OnServerValidate="validateCountry"
    Text="Please enter Country Name"
    runat="server"/>

The OnServerValidate property of the CustomValidator calls the server side function validateCountry.

Here is the server side (code-behind) function

public void validateCountry(object source, ServerValidateEventArgs args)
{
    if (drpCountry.SelectedValue != "Others")
    {
        args.IsValid = true;
        return;
    }
    //
    if (txtName.Text.Trim().Length == 0)
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}

Now if you try to save the form by selecting Others in the drpCountry DropDownList with an empty value in the txtName TextBox then the validation fires and displays the message.

Please enter Country Name

That’s it we have seen the usage of a CustomValidator with server side validation.


9-Disable asp.net validation controls in JavaScript 

In this post Disable asp.net validation controls in JavaScript; we will see on how to disable Asp.Net validation controls using JavaScript.

Asp.net validation controls are server side controls, but we might need to disabled them at times, these controls can be disabled from the server side code using the .Enabled property as follows.
validateName.Enabled = false;

But, disabling the controls from the code-behind will require a page post back; to avoid this we can disable the Validation controls from the client side using Java Script as follows.

var myValidator = document.getElementById('validateName');
ValidatorEnable(myValidator, false);

You might wonder that we have not defined the function ValidatorEnable, and might throw an error, but no errors will be thrown, this is a Built in function in Asp.Net



Here is a full example
<script type="text/javascript">
function DisableValidator(checked)
{
    if (checked == true)
    {
        var myValidator = document.getElementById('validateName');
        ValidatorEnable(myValidator, false);
    }
}
</script>

Enter Name:
<asp:TextBox
    ID="txtName"
    runat="server">
</asp:TextBox>

<asp:RequiredFieldValidator
    ID="validateName"
    runat="server"
    ControlToValidate="txtName"
    ErrorMessage=" Please enter Name"
    Display="Dynamic">
</asp:RequiredFieldValidator><br />

Disable Validator:
<input
    type="checkbox"
    value="Disable Validator"
    onclick="javascript:DisableValidator(this.checked);" /><br />

<asp:Button
    ID="cmdSave"
    runat="server"
    Text="Save" onclick="cmdSave_Click"/>

In the above example when the Disable Validator checkbox is checked, the validator validateName is disable, hence the user can submit the form without entering the name, but when the checkbox is not checked the user is prompted with an error message Please enter Name, when the txtName TextBox is empty

No comments :