Click here to Skip to main content
Click here to Skip to main content
Go to top

Introduction to ASP.NET validation

, 16 Apr 2012
Rate this:
Please Sign up or sign in to vote.
Client side validation using JavaScript and server side validation using C# and validation server controls with simple examples.

Introduction

In here I discuss about client side validation using JavaScript and server side validation using C# and validation server controls with simple examples.

What is input validation

It verifies control values entered correctly and block page processing until the control values are valid. This is very critical to application security. Validation can be done in serve side or client side.

Client side validation

Use JavaScript for client validation. JavaScript can be slightly different between browsers and some old browsers do not support JavaScript. So when writing JavaScript we have to deal with the differences between browsers.

When user submits a page, before it is submitted to the server, it is caught by JavaScript and checks for validation. If there are errors it prevents from submitting to the server. So in here we can get a immediate feed back without having a trip to the server. It reduce the post backs and network traffic.

Using code

First open Visual Studio 2010 and create a new ASP.NET empty web application. (File -> New -> project ->ASP.NET Empty Web Application) Then add a new web form to the project (right click project -> Add ->New Item).

Add text boxes for username and email and labels to display error messages and a submit button  to the web form.

<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:Label ID="LabelValidateName" runat="server"></asp:Label>
<asp:TextBox ID="TextBoxEmail" runat="server"></asp:TextBox>
<asp:Label ID="LabelValidateEmail" runat="server"></asp:Label>
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" />

Then go the source view and add the following JavaScript code in head tag.

<script type="text/javascript">
function validateForm() {

var count = 0; //variable to store the error count
//validate Username
var x = document.forms["form1"]["TextBoxName"].value;
//gets the textbox value to variable x
if (x==null || x=="") //if x is empty
{
document.getElementById("LabelValidateName").innerHTML = "Username Required";
count++;
}
else {
var alphaExp = /^[a-zA-Z]+$/; //regular expression of a word only consists of letters
if (!x.match(alphaExp)) { //match x with the regular expression

document.getElementById("LabelValidateName").innerHTML = "Only letters allowed";
count++;
}else{
document.getElementById("LabelValidateName").innerHTML = ""; //clear the error label

}

}
//validate email address
x = document.forms["form1"]["TextBoxEmail"].value;
if (x == null || x == "") {
document.getElementById("LabelValidateEmail").innerHTML = "Email Required";
count++;
}
else {
alphaExp = /^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$/; //regular expression of a valid email address
if (!x.match(alphaExp)) {

document.getElementById("LabelValidateEmail").innerHTML = "Check the Email format";
count++;
} else {
document.getElementById("LabelValidateEmail").innerHTML = "";
}
}
if (count == 0)
return true; //if no errors return true
else
return false;
}
</script>

In this script first we get the value in the textbox to variable x and  check whether it is empty. then we check for correct format using regular expressions. if there is a  error display the error in the label.

Now we have to call this JavaScript function before page submits to server. To do that use onsubmit in the form tag.

<form id="form1" runat="server" onsubmit="return validateForm();">

Now when we press the Submit button before submitting to the server it check for the return value of validateForm() function. It submit to the server only when the return value is true. If there are errors it will display errors without submitting to the server.

Server side validation

In here validation is done in the server after submitting the page to the server using managed code. Basically server side validation duplicate the client side validation and it may seem redundant. But we have to do it because some old browsers do not support JavaScript and also someone can create a custom browser program which do not support JavaScript.

In server side validation we can go beyond client side validation and use some server side logic which available on the server. This can be done using C# and ASP.NET validation server controls. First lets see how to do validation without server controls in the server.

Server side validation using C#

Add a new ASP.NET empty web application to the current solution( right click solution -> Add -> New Project ). Then add a new web form to the project and add  text boxes for username and email and labels to display error messages and a submit button  as in the previous example.

Then double click the Submit button and add the following code to ButtonSubmit_Click(object sender, EventArgs e).

if (string.IsNullOrEmpty(TextBoxName.Text))
{
LabelValidateName.Text = "Username required";
}
else if (!checkValidString(TextBoxName.Text))//check with regular expression
{
LabelValidateName.Text = "Only letters";
}
else
LabelValidateName.Text = null;

if (string.IsNullOrEmpty(TextBoxEmail.Text))
{
LabelValidateEmail.Text = "Email required";
}
else if (!checkValidEmail(TextBoxEmail.Text))
{
LabelValidateEmail.Text = "check the format";
}
else
LabelValidateEmail.Text = null;

Also add these two functions to the .cs file which check the input strings with regular expressions.

public bool checkValidString(string input)
{
const string regExpr = @"^[a-zA-Z]+$"; //regular expression for valid string
// match input with regular expression
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, regExpr);
if (m.Success)
{
return true;
}
else
{
return false;
}
}

public bool checkValidEmail(string input)
{
const string regExpr = @"^(?("")("".+?""@)|" + 
      @"(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)" + 
      @"(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])" + 
      @"|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$";
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, regExpr);
if (m.Success)
{
return true;
}
else
{
return false;
}
}

In here first check whether the textboxes are empty. Then we check for correct format using regular expressions. If there is a  error display the error in the label.In the previous example validation is done in the client side using JavaScript and in here in the server side using managed code (C#, VB).

Server side validation using ASP.NET validation server controls

In the previous examples we have to write certain amount of code for validation. But with validation server controls validation can be done with less amount of code. As in the previous examples we don’t need labels to display errors. Only thing we have to do here is add a server control and set properties. There are five validators provided by ASP.NET. One more control is also provided ValidationSummary that is used to display the validation messages as a summary.

ASP.NET Validators

  • RequiredFieldValidator
  • RangeValidator
  • RegularExpressionValidator
  • CompareValidator
  • CustomValidator
  • ValidationSummary

First let's talk about the basic properties common to all the validators.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ValidatorType ID="id"runat="server"
ControlToValidate="TextBox1"
Display="Static|Dynamic|None"
Text="Error message on target"
ErrorMessage="Error message">
</asp:ValidatorType>

I have wrote the above code just to give you a basic idea about validation controls (not a valid code). Every validator has a ControlToValidate property and here it is set to TextBox1 (TextBox ID). It means TextBox1 should be validated using this control. In the Display property there are three options as shown above. If u select Static validation server control take up space with in the page even there are no error messages visible. So multiple controls cant occupy the same space within the page. If u select Dynamic the control only take space when there is a message to display. If u select None control will not appear on the page.

ErrorMessage property sets the error message which can be displayed in the optional ValidationSummary control and Text property sets the error message which display within the validation server control.

RequiredFieldValidator

<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName"
runat="server" ControlToValidate="TextBoxName"
Text="*" ErrorMessage="Required">
</asp:RequiredFieldValidator>

we use this control for required fields when we are mandating the user input for any particular field.

RangeValidator

<asp:TextBox ID="TextBoxAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBoxAge" ErrorMessage="RangeValidator" MaximumValue="30"
MinimumValue="20" Type="Integer">must be between 20-30</asp:RangeValidator>

In scenarios where we want to ensure that the value entered by the user is in some predefined range, we can use this control. In above example user need to enter value between 20-30.

RegularExpressionValidator

<asp:TextBox ID="TextBoxEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBoxEmail" ErrorMessage="Check EMail format"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">Check the format</asp:RegularExpressionValidator>

This control can be used when we want the input to be in specific format. In the above example I have checked for valid Email address using a regular expression.

CompareValidator

<asp:TextBox ID="TextBoxConfirmEmail" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="TextBoxEmail" ControlToValidate="TextBoxConfirmEmail"
ErrorMessage="CompareValidator">Email address dont match</asp:CompareValidator>

This Validation server control is used when we want to compare two values. In the above example it validates TextBoxConfirmEmail by comparing it with TextBoxEmail.

CustomValidator

<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Name cannot be NULL" ControlToValidate="TextBoxName"
OnServerValidate="validateName">Name cannot be NULL</asp:CustomValidator>

public void validateName(Object source, ServerValidateEventArgs args)
{
args.IsValid = args.Value.ToLower() != "null";
}

In Custom Validator we can specify a JavaScript code as ClientValidationFunction or server side code as OnServerValidate and write our own validation logic. In the above example I have used server-side code to check whether the name equals null.

ValidationSummary

<asp:ValidationSummary ID="ValidationSummary1" runat="server"
HeaderText="Errors" />

Validation summary control checks all the validation controls and display ErrorMessages as a summary.

Using Page.IsValid property we can check for page errors. When there are no errors IsValid returns true and user can proceed to next page.

if (Page.IsValid)
{
  //validation complete proceed
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dhanushka Madushan lk
Software Developer
Sri Lanka Sri Lanka
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 16 Apr 2012
Article Copyright 2012 by Dhanushka Madushan lk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid