Click here to Skip to main content
12,956,173 members (63,387 online)
Click here to Skip to main content
Add your own
alternative version

Stats

27.7K views
2 bookmarked
Posted 16 Apr 2012

Introduction to ASP.NET Validation

, 16 Apr 2012 CPOL
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 server 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 an immediate feedback without having a trip to the server. It reduces the post backs and network traffic.

Using the 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 an 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 checks for the return value of validateForm() function. It submits 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 duplicates 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 does not support JavaScript.

In server side validation, we can go beyond client side validation and use some server side logic which is available on the server. This can be done using C# and ASP.NET validation server controls. First, let's 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 an 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 a 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 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 you select <span style="color: rgb(0, 0, 0);">Static</span> validation server control take up space within the page even there are no error messages visible. So multiple controls can't occupy the same space within the page. If you select Dynamic, the control only takes space when there is a message to display. If you 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 displays 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 the above example, user needs 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 displays 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 the 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

You may also be interested in...

Comments and Discussions

 
Questiongood article Pin
Er.Vaibhav Singh Chauhan30-Oct-15 2:21
professionalEr.Vaibhav Singh Chauhan30-Oct-15 2:21 
Questiongood article Pin
Er.Vaibhav Singh Chauhan30-Oct-15 2:53
professionalEr.Vaibhav Singh Chauhan30-Oct-15 2:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170525.1 | Last Updated 16 Apr 2012
Article Copyright 2012 by Dhanushka Madushan lk
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid