Understanding ASP.NET Validation Techniques
原文链接:http://www.codeproject.com/Articles/334310/Understanding-ASP-NET-Validation-Techniques
Introduction
This article aims at understanding the basic validation techniques and controls provided by ASP.NET framework. We will try to understand which validation control should be used in any particular scenario and then make a small dummy application to illustrate the use of validation controls.
Background
Whenever we have an application that expects user input, then it becomes important to ensure the validity of the data input by the user. We might have scenarios when some data is mandatory for the user to enter. There are scenarios when the user data has to be in some particular format example email ID. There could be scenarios when we want the data to be in some range example date input.
So for all the above mentioned scenarios, if we take the user input without validation, then chances are that we will end up having wrong data with us (perhaps in database). If it is a bad day for us then possibly our application might also end up behaving in an unexpected manner and even crash on us (like if we try to convert a non numeric string
to int
). Worst case scenario, the user will use the input field to perform SQL injection and cause serious damage to our database. So it is always a good idea to have validation in place whenever we are taking input from the user.
Types of Validation
There are two ways we can perform validation:
- Client side validation
- Server side validation
Client Side Validation
Client side validation is something that will happen on users‘ browser. The validation will occur before the data gets posted back to server. It is a good idea to have client side validation as the user gets to know what needs to be changed immediately, i.e., no trips to servers are made. So from the users‘ point of view, it gives him fast response and from the developers‘ point of view, it saves valuable resources of server.
JavaScript is most widely used to perform client side validation. From decades, developers have been using JavaScript for client side validation. It is always a good idea to have knowledge of JavaScript as it gives us full control over client side validation. Now Microsoft is also embracing jQuery in its current versions so perhaps JavaScript and/or Jquery should be the right thing to use for client side validation.
JavaScript provides full control to the developer on how client side validation should happen but developers will have to write the validation code themselves. ASP.NET also provides some validation controls to perform client side validation which could help the developers in putting client side validation in place without writing a lot of code. These controls will also use JavaSscript underneath to perform validations. We will see these controls in a moment.
Server Side Validation
Server side validation occurs at server. The benefit of having server side validation is that if the user somehow bypasses the client side validation (accidentally or deliberately), then we can catch the problem on the server side. So having server side validation provides more security and ensures that no invalid data gets processed by the application.
Server side validation is done by writing our custom logic for validating all the input. ASP.NET also provides us some controls which will facilitate the server side validation and provides a framework for the developers to do the same.
NOTE: Web developer may choose to go with any one type of validation but usually it is a good idea to have client side validation and same validation on server side too. It sure takes some resources of server to validate the already validated data (on client side) but it ensures security and that is always good.
Validation Controls in ASP.NET
The validation controls provided bt ASP.NET are:
RequiredFiledValidator
CompareValidator
RangeValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
We can tweak these validation control‘s properties for how to perform validation but first let us look at some properties common to all these controls.
ControlToValidate
: ID of the control which should be validated by this control.ErrorMessage
: This message will be displayed to the user when validation fails. This should always be something which user can read and act upon.Text
: Thisstring
will be visible where the validation control is placed when validation fails. Usually it is a good idea to set it to "*".
There are few more properties but for now we can move ahead with these properties in mind and see all the validation controls in action.
Validation Summary
It is a good idea to look at this control first. ValidationSummary
control is a control which displays the error messages for all the validation controls on the page in one place. If we want to have this control display the error messages for some particular validation controls (possibly because we have multiple ValidationSummary
on page), then we can use ValidationGroup
property of the controls. Let‘s move ahead and see how validation summary will be useful for us.
RequiredFieldValidator
This validation control will be used when we are mandating the user input for any particular field. Let‘s say we have a simple form with name field and we don‘t want this to be empty. so what we can do is add aRequiredFieldValidator
to the page, set the ControlToValidate
to the ID of the name input field, set the error message property.
When we try to do a postback without entering name, then the postback will not happen and the "*" will be displayed in place to our validation control. The ValidationSummary
we already added will display the full error message.
If we look at the timestamp we added on the page, we can verify that the validation is happening on the client side and no postback is happening to the server. If we need to change this to do this validation in server side, then we will have to set the EnableClientScript
property of the validation control to false
.
CompareValidator
This control will compare the value of its ControlToValidate
with ControlToCompare
. It uses the comparison operators to do the same. Now let us say we have a hypothetical scenario where we want the same name to be entered twice (not so hypothetical if it would be password) then we can have a CompareValidator
in place with the following properties:
In case we want this control to use some predefined value instead of value in some control, then we can useValueToCompare
property.
Now let‘s run the page:
If we look at the timestamp we added on the page, we can verify that the validation is happening on client side and no postback is happening to the server. If we need to change this to do this validation in server side, then we will have to set the EnableClientScript
property of the validation control to false
.
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. Let us try to add this control on our page and use this to validate the age of the user. We are saying the valid age is between 18 to 50.
When we run the page:
If we look at the timestamp we added on the page, we can verify that the validation is happening on the client side and no postback is happening to the server. If we need to change this to do this validation in server side, then we will have to set the EnableClientScript
property of the validation control to false
.
Regular Expression Validator
RegularExpressionValidator
comes in handy when we want input data to be in some specific format. Let us try to do that on our page by asking the user for his email ID. We will be using theRegularExpressionValidator
for validating the format of email id.
Let us run the page.
CustomValidator
If with all these validation controls provided by ASP.NET, we still find ourselves a scenario where we need customized validation behavior, we can use the CustomValidator
Control. Let us try to use this control and perform custom client side as well as server side validation. What we will do is we will check for ‘-‘ character in user input and reject the input if ‘-‘ is present in any field (assuming a SQL injection attempt). So let us see how can we use CustomValidator
for it.
Now let us look at the client side JavaScript we had to write to provide our custom validation behavior:
function ValidateOnClient(source, arguments) { if( arguments.Value.search(‘-‘) != -1) { arguments.IsValid = false; } }
and when we run the page:
Now let us do the same by having the validation done at server side. We will do that for the email id field.
protected void CustomValidator2_ServerValidate (object source, ServerValidateEventArgs args) { string value = args.Value; if (value.Contains("-")) { args.IsValid = false; } }
When we enter invalid data in email id field, the validation error will be displayed after postback.
Summary
Although we can do all the client side and server side validations ourselves using JavaScript and server side code, we could find the validation controls provided by ASP.NET useful in many scenarios. These validation controls give us the flexibility of validating on client side or server side. We can use the ValidationGroup
,Page.IsValid
properties and Page.validate
method to have fine grained control on the validation process.
History
- 22 Feb 2012: Understanding ASP.NET validation techniques
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。