Click here to Skip to main content
15,884,537 members
Articles / Web Development / ASP.NET
Tip/Trick

Single Server Side Validator for Multiple Controls

Rate me:
Please Sign up or sign in to vote.
4.87/5 (11 votes)
22 Apr 2014CPOL3 min read 26.6K   13   7
Single Server side validator for multiple controls

Introduction

I was having a requirement where I had to validate multiple controls with a single validator. It was challenging when it was asked to write on server side. The client side validation can be easily bypassed. This post concentrates on the Server side validation only. We should always provide both client and server side validation.

Background

To find the solution for the above said requirement, I found a post on CodeProject for Using Single validator for multiple control which works on client side thus introduces security concerns. It did not fit my requirement. I spent a fair amount of time over the net and could not find any post on this. After struggling for quite a lot of time on Validators, I found a solution, hence sharing with others.

In this post, I have created a sample application which will validate the first name and last name two different text box using one validator. I am using regular expression to validate my text box.

Quote:
You should always have the combination of client side and server side validation for the controls. Client side validation can be bypassed easily by malicious user or code. Server side validations are guaranteed to be run where applicable.

Using the Code

I have created a sample application which will validate the first name and last name using regular expression. This is using single custom validator. Screen-1 shows the main page layout.

Image 1

Screen-1

If user enters the wrong input for the first name or last name, then validator validates the inputs. In the sample application, I have provided validation for the mandatory fields and alphabets from a to z or A to Z. Screen-2 below shows the error display by the custom validator.

Image 2

Screen-2

If entered text is proper, then it displays a right tick icon image which is set to visible = true in code behind file. You can do any other action if you want. (Refer Screen-3)

Image 3

Screen-3

Let's Do Some Code

In this sample, I have created two Text boxes:

ASP.NET
<td>First name
     <asp:TextBox id="Text1" runat="server"  />
</td>
<td>Last name
     <asp:TextBox id="Text2" runat="server" />
</td>

And a button button1 to trigger the server side post back and to initiate the validation.

ASP.NET
<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="ValidationClicked" ValidationGroup="CustomerNameValidation" />

The main problem starts with the validators as they all are having a property called ControlToValidate. This property can contain only one target control name. To achieve our requirement, I marked it as blank string. Please note that I have marked the ValidationGroup="CustomerNameValidation". This is the same as it is Marked for the Button1 Control. So ValidationGroup name must be same for Button1 and CustomValidator.

ASP.NET
<asp:CustomValidator id="CustomValidator1"
                                         OnServerValidate="ServerValidation"
                                         ControlToValidate=""
                                         Display="Dynamic"
                                         Text=""
                                         ErrorMessage='<img src="Resources/CrossTick.png"/> Only alphabets allowed'
                                         ForeColor="green"
                                         Font-Name="verdana"
                                         Font-Size="10pt"
                                         ValidationGroup="CustomerNameValidation"
                                         runat="server"
                        />

On the Code behind page to handle the Button1 Onclick event, we write the below event handler:

C#
protected void ValidationClicked(object sender, EventArgs e)
  {
    if (Page.IsValid)
      imgRightTick.Visible = true;
  }

If the Page is valid, in my case I am showing a tick image icon for the successful.

As you can see, the CustomValidator control's OnServerValidate property is assigned with "ServerValidation" event handler which is written in code behind. The code for event handler is written below.

C#
protected void ServerValidation(object source, ServerValidateEventArgs arguments)
   {
     if(string.IsNullOrWhiteSpace(this.Text1.Text) || string.IsNullOrWhiteSpace(this.Text2.Text))
     {
       arguments.IsValid = false;
       return;
     }
     Regex regex = new Regex("^[a-zA-Z]");
     if(!regex.IsMatch(this.Text1.Text))
     {
       arguments.IsValid = false;
       return;
     }
     if (!regex.IsMatch(this.Text2.Text))
     {
       arguments.IsValid = false;
     }
   }

Note that we are not using the arguments.Value property as it is specific to a single control. We can directly access any controls property and validate based on any criteria. If validation is unsuccessful, then set the arguments.IsValid = false and return. It will display the error message associated with the custom validator.

Note:
To use the Regex class, you will have to include the statement "using System.Text.RegularExpressions;" in code behind file.
Quote:
You should always have the combination of client side and server side validation. In this CustomValidator, you can easily assign the client side validation using ClientValidationFunction.

This is all I wanted to share. Suggestions are always welcome.

License

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


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Volynsky Alex23-Apr-14 21:33
professionalVolynsky Alex23-Apr-14 21:33 
GeneralRe: My vote of 5 Pin
Jitendra_Shri24-Apr-14 8:35
Jitendra_Shri24-Apr-14 8:35 
GeneralRe: My vote of 5 Pin
Volynsky Alex24-Apr-14 12:44
professionalVolynsky Alex24-Apr-14 12:44 
QuestionDoubt regarding imgRightTick Pin
dileeppeddinti22-Apr-14 21:42
dileeppeddinti22-Apr-14 21:42 
AnswerRe: Doubt regarding imgRightTick Pin
Jitendra_Shri24-Apr-14 8:12
Jitendra_Shri24-Apr-14 8:12 
QuestionBig Help.. Thanks.!! and small addition for target framework 4.5 Pin
Ullas Kumar6-Feb-14 21:22
Ullas Kumar6-Feb-14 21:22 
AnswerRe: Big Help.. Thanks.!! and small addition for target framework 4.5 Pin
Jitendra_Shri7-Feb-14 3:37
Jitendra_Shri7-Feb-14 3:37 

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.