User Input Validation in ASP.NET

HTML forms exist to collect data from the user. And this data, like every piece of user input, needs to be checked first for both security and logical reasons (what could we do with irrelevant data). There are two ways of checking the validity of user input: on the client side, and on the server side. Client side validation is swifter and more elegant, then posting back the data to the server, and the send back and error message. But we must implement both validation techniques, because a crafty attacker can bypass our client-validating methods, and send for example scripts or SQL commands back to our page to process them.

Implementing these two different approaches is quite tedious by hand, because client-side validation usually takes place in javascript, while server-side logic could be PHP, or in our case C#, and they are very different by their nature. And there come the ASP.NET validation controls in the picture.

ASP.NET Validation Controls
RequiredFieldValidator Checks that a given field in the form isn’t empty (or its default data has been changed) on submit.
RangeValidator Checks that the given value is within a specific range – numerical, string or date.
CompareValidator Compares a value of a specific control to a static value (less, greater, equal, identical), or another control.
RegularExpressionValidator Checks whether a given control’s value matches a regular expression.
CustomValidator Allows you to build up your own client- and server-side validation logic.
ValidationSummary Shows a summary of validation errors for your page on submit.

 

More than one validation control can work on a control, but every control has one and only one property, which can be validated. When building custom control, you can specify this property with the ValidationPropertyAttribute.

The Validation Process:

You can control your page’s validation behavior. Generally, it makes sense to validate a form, when the user is about to submit it. And this can generally be done with a button. Set the button’s CausesValidation to true (or don’t set it to anything, since this is the default), and when the user clicks on it, validation will take place. Set it to false, and there won’t be any. Please note that there is a property to control the client-side validation too, but it can be set individually for each validator. This is called EnableClientScript, and accepts a Boolean value.

Furthermore, you can specify groups of controls, which should be validated together, with one or more controls (such as buttons) that will trigger their validation, by using the ValidationGroup property.

When you want to check if a control is valid, you can call its IsValid property. But be aware of that you can only use it, when client-side validation did not run. A more comfortable approach is the Page.IsValid property, which shows you if all controls are passed validation on your page.

CustomValidator:

The one validation control which worth a little more explanation is CustomValidator. You can use it in the case if the supplied validator controls aren’t enough for a specified task. It lets you define your custom client and server-side validation logic, with the following implementation:
<asp:TextBox runat=”server” ID=”MyBox”/>
<asp:CustomValidator runat=”server” ControlToValidate=”MyBox” ClientValidationFunction=”CheckMyBoxClient” OnServerValidate=”CheckMyBoxServer” ErrorMessage=”Value isn’t even!”/>

Now, the client-side validation logic:

<script type=”text/javascript”>
function CheckMyBoxClient(sender, args)
{
    args.IsValid = (args.Value%2==0);
}
</script>

Then the server side:

protected void CheckMyBoxServer(object sender, ServerValidateEventArgs args)
{
     try
      {
        args.IsValid = (int.Parse(args.Value)%2==0);
      }
     catch
      {
        args.IsValid = false;
      }
}

Accessing Validation Controls from Code:

You can validate a page, or a validation control, calling the Validate method, which sets the IsValid property. Checking that property can help you determine whether your page/control is valid or not.

You can also set some aspects of the validation process, by setting validator controls Enabled, EnbleClientScript properties. You can even validate only specific validation groups, calling Page.Validate(“GroupName”).

Advertisements

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: