ASP.NET Validations Tips and Tricks Part-III

Sheonarayan
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 11318 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article we shall learn how to validate a valid email address entered into the textbox, how to compare two textboxes for equality, like password and confirm password, how to perform custom validation in ASP.NET and how to display all validation failed errors in the Alert box or as a summary.

Introduction

Validation controls are used to validate the ASP.NET input server controls like asp:TextBox for valid data when their data is submitted to the server.

There are six validation controls in ASP.NET and they are

    1. RequiredFieldValidator
    2. RangeValidator
    3. CompareValidator
    4. RegularExpressionValidator
    5. CustomValidator and
    6. ValidationSummary

Get ASP.NET, ADO.NET, jQuery, HTML, CSS and JavaScript How to Tips and Tricks, click here.

This article is in continuation of my previous article on ASP.NET Validation control topic, click here to read.

Now lets learn Tips and Tricks related with ASP.NET Validation controls in continuation of the last article.

How to validate a valid email address entered into the textbox?

In case we want to check whether a valid email id has been entered into the TextBox or not, we can follow this approach.

ASPX PAGE

Your email: <asp:TextBox ID="txtEmail" runat="server" Columns="50" /> <br />

<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory !" ControlToValidate="txtEmail" ForeColor="Red" />


<asp:RegularExpressionValidator ID="ReExp1" runat="server"

ControlToValidate="txtEmail" ErrorMessage="eg. abc@domain.com"

ForeColor="Red"

ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-

.]\w+)*"></asp:RegularExpressionValidator>

 

<p><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitData" /></p>

 

CODE BEHIND

protected void SubmitData(object sender, EventArgs e)

{

}

 

In the above code snippet, we want to validate the TextBox for correct format of the email id. For that we have used asp:RegularExpressionValidator with ValidationExpression as “\w+([-+.']\w+)*@\w+([- .]\w+)*\.\w+([-.]\w+)*” that validates the TextBox data for correct email id format (eg. abc@domain.com).

We have used asp:RequiredFieldValidator to force user to enter some data into the TextBox.

OUTPUT


How to compare two textboxes for equality, like password and confirm password?

To check if values of two controls (eg. TextBox) are same or not, we can follow this approach.

ASPX PAGE

<p>

Password: <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />

<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory

!" ForeColor="Red"

ControlToValidate="txtPassword" /></p>

 

<p>

Confirm password: <asp:TextBox ID="txtPasswordC" runat="server"

TextMode="Password" />


<asp:CompareValidator ID="comp1" runat="server" ErrorMessage="Both password

must match"

ControlToValidate="txtPassword" ControlToCompare="txtPasswordC"

Operator="Equal"

Type="String" ForeColor="Red" />


</p>

<asp:Button ID="btnCheck" runat="server" Text="Submit" />

In the above code snippet, we have two TextBoxes with TextMode as "Password". We want user to enter the same password in both TextBoxes. To validate this, we can use asp:CompareValidator with ControlToValidate attribute to the first textbox and ControlToCompare as the second textbox, apart from that we need to also set Operator attribute to o “Equal” and Type attribute as “String”.

OUTPUT


How to perform custom validation in ASP.NET?

To perform custom validation in asp.net, we can follow this approach. If our validation is of custom type and asp.net in-built validation controls can’t be used then we can use this approach to write custom validation for a particular textbox or other controls.

ASPX PAGE

<p>

<asp:Label ID="lblMessage" runat="server" ForeColor="Red" EnableViewState="false" /></p>

Enter even number: <asp:TextBox ID="txtEven" runat="server" ClientIDMode="Static" />


<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Mandatory !" ControlToValidate="txtEven" ForeColor="Red" />


<asp:CustomValidator ID="Cust1" runat="server" ControlToValidate="txtEven" ClientValidationFunction="CheckForMode"ErrorMessage="Enter only even number" OnServerValidate="CheckForMode" ForeColor="Red" />

<p>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitData" /></p>


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

function CheckForMode(source, arguments) {

var element = document.getElementById('txtEven').value;

var mode = element % 2;

if (mode == 0) {

arguments.IsValid = true;

}

else {

arguments.IsValid = false;

}

}

</script>

 

CODE BEHIND

protected void SubmitData(object sender, EventArgs e)

{

}


protected void CheckForMode(object sender, ServerValidateEventArgs e)

{

int number = int.Parse(e.Value);

var modeResult = number % 2;


if (modeResult.Equals(0))

{

e.IsValid = true;

}

else

{

e.IsValid = false;

lblMessage.Text = "Sorry, please enter even numbers only";

}

}

 

In the above code snippet, we have a TextBox and we want to validate for the even numbers into this TextBox. As there is no in-built validation control available to validate even number, we can use asp:CustomValidator.

asp:CustomValidator accepts the ControlToValidate (the TextBox that we want to validate), ClientValidationFunction (in our case CheckForMode function - the JavaScript function that should be called to validate the TextBox data) and OnServerValidate (in our case CheckForMode method - the server side method to validate the TextBox data - optional. This function name not necessarily should be the same name as the Client side function). Any one, either ClientValidationFunction or OnServerValidate is mandatory.

In the CheckForMode javascript function, we have checked for the mode of the TextBox value into theTextBox, if it is even then we are specifying arguments.IsValid property to true otherwise false. If it will be false, an error message will be displayed (that is mentioned as ErrorMessage property).

asp:RequiredFieldValidator control has been used to force user to enter some data into the TextBox.

OUTPUT

How to display all validation failed errors in the Alert box or as a summary?

To consolidate all validation errors occurred on the page and show them in the alert or bulleted list on the page, we can follow this approach.

ASPX PAGE

 

<p>

Enter your name: <asp:TextBox ID="txtName" runat="server" /> *

<asp:RequiredFieldValidator ID="req1" runat="server" ErrorMessage="Enter your

name" ForeColor="Red" ControlToValidate="txtName" /></p>

<p>

Enter your address: <asp:TextBox ID="txtAddress" runat="server" /> *

<asp:RequiredFieldValidator ID="req2" runat="server" ErrorMessage="Enter your

address" ForeColor="Red" ControlToValidate="txtAddress" /></p>

<p>

Enter your age: <asp:TextBox ID="txtAge" runat="server" /> *

<asp:RequiredFieldValidator ID="req3" runat="server" ErrorMessage="Enter your

age" ForeColor="Red" ControlToValidate="txtAge" /></p>

 

<asp:ValidationSummary ID="ValSum1" runat="server" ForeColor="Brown"

ShowMessageBox="true" ShowSummary="true" />

 

<asp:Button ID="btnCheck" runat="server" Text="Submit" />

In the above code snippet, we have three TextBoxes and all are mandatory. To show the validation failed error in alert box or summary, we can use asp:ValidationSummary control. Setting ShowMessageBox property to true enables the client side alert box (uses javascript) to display and ShowSummary to true (default is true) enables the summary to be displayed as shown in the below picture.

OUTPUT


Hope you are enjoying my series of tips and tricks in ASP.NET. Get the video tutorials of hundreds of Tips and Tricks from here.

Thanks for reading, keep learning and sharing your knowledge on www.dotnetfunda.com !

Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)