Form Validation

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

A form is quite a common element found scattered across web sites. In order to sign in or buy some stuff, we will most probably be presented a list of boxes we will have to fill in. If, however, by mistake you insert in English character within your telephone submission, you are likely to get a notice mentioning that a phone number is meant to contain nothing but numbers. Likewise, most data we submit is examined so that only correct type of info will get inside the website's storage. In this article we will see how JavaScript can help in this as well as ASP.NET's validation controls. We will also see how we can create captcha controls for our website.
 

Getting Started

There are two types of validation. Client side and server side validation. Client side validation refers to validation using JavaScript or ASP.NET validation controls. It takes place on the client's browser. On the other hand, server side requires a new request and will do the validation on the server.
 
At first glance, client side validation seems to be really nice. For example, suppose we wanted to inform the user if the email he has inserted is correct. Using client side validation the moment he inserts his email, it will be validated using JavaScript and he will see the notice in his screen right away. Now, what would happen if we had used server side control? The user would write down his email, the page would post back to the server, the server would do the validation and return the response containing the notice. Apart from being time and resource consuming, the user would see his page created all the way from the beginning every time he filled a box. That's a great way to irritate him and make him take one more step towards never returning to your site.
 
So, client side validation seems to be really nice. However there's still some problem here. Client side means JavaScript and JavaScript can be handled by the user. Well, not by all users, but there are users that may bypass your validations and insert the info they want. There are also some users who may have JavaScript turned off. That's the reason why, even though server side validation is nasty to use, we do need it.
 
The best way to validate your form is use both client and server side validation. While the user fills in his form we inform him of possible mistakes client sided. When the user fills his form, he will hit the submit button. That's when the server side validation should take place and relieve us of possible JavaScript problems.
 
 

Using JavaScript

JavaScript is the classic way to validate the input. JavaScript can do almost everything, so we will just take a look at a few examples in order to lead the way.
 
This will be our JavaScript form. It consists of three fields: a name field, an email field and a phone filed.
 
JavaScript Validation
    <table>
        <tr>
             <td>Name</td>
            <td><asp:TextBox runat="server" ID="NameID" onblur ="checkForEmpty(this.value, 'Name');"  /></td>
        </tr>
         <tr>
            <td>Phone</td>
            <td><asp:TextBox runat="server" ID="PhoneID" onblur ="checkNumber(this.value);" /></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><asp:TextBox runat="server" ID="MailID" onblur ="checkEmail(this.value);"  /></td>
        </tr>
    </table>
 
 
There are three things we want to ensure.
  1.  The Name is always filled.
  2. The phone consists of number characters.
  3. The Email has the typical email format.
 
 
As mentioned, we are using plain JavaScript. Each TextBox has a function set to its onblur event. This means that when the user removes his attention from the TextBox, the function mentioned will run. Every one of them gets this.value as an argument. This is the value of the TextBox.
 
For example if we write "Sam" inside the NameID TextBox, this.value will be "Sam".
 
checkForEmpty should check if the NameID TextBox has value. So, all we have to do is check if this.value is an empty string. This will be the function checkForEmpty.
 
        function checkForEmpty(name, valueName) {
            if (name == "")
                alert("You have to fill in your " + valueName);
        }
 
If the box is empty we will get an alert box, stating so. We have also used the valueName argument, so the message can contain info on what box needs to be filled.
 
 
form validation- javascript-error
 
checkNumber should check if the value of the PhoneID TextBox is a number. An easy way to do this is using regular expressions.
 
We are not going to discuss much about regular expressions here, since it is quite a complex point. We will just say that regular expressions are just a way to describe the form a value's characters have. For example, an integer is expected to contain number characters only. A name and surname, is expected to contain English characters only containing a space character.
 
The regular expression we are about to use is this /^\d+$/. This will spot all values that contain digits. The match method will return true if the given regular expression matches the input. Here's the function.
 
        function checkNumber(number) {
            var numberRegEx = /^\d+$/;
 
            if (!number.match(numberRegEx)) {
                alert("The number you inserted is not accepted.");
            }
        }
 
form validation- javascript-error
 
checkEmail should check if the value of the MailID TextBox is the typical email format. We are going to use regular expressions over here as well. However, in the case of email regular expressions there is no ultimate solution. There are many regular expressions meant to match emails and we can choose whatever we want. In the following example we will use a quite simple solution.
 
/.*@.{2,}\..{2,}/
 
This regular expression expects the value to contain characters, followed by '@', followed by two or more characters, followed by '.', followed by two or more characters. For example, bob@mail.com is correct. This structure is nothing more than a naive approach.
 
So, the method will look like this.
 
function checkEmail(email) 
        {
            var emailRegEx = /.*@.{2,}\..{2,}/;
 
            if (!email.match(emailRegEx)) {
                alert("The email you inserted is not accepted.");
            }
        }
 
form validation- javascript-error2
 
 

Validation Controls 

That was the way JavaScript handles validation. We are now going to see how ASP.NET may be of use. Validation controls are asp controls that can easily validate input. Validation controls can be run either in the client or in the server.
 
Here are a few things concerning input validations, common to all controls.
 
First is the ControlToValidate attribute. This is the ID of the control they are validating. Next follows the Text. This is the literal that will appear where the validator stands in case of failed validation. If the validation succeeds nothing shows up. SetFocusOnError is one more interesting attribute. In case we validate all controls and we fail, the focus will be set to the control that failed.
 
Validation controls mostly work on client side (independently in case more than one exist) executing JavaScript methods. However there will be a time when the user should do something to submit the form, for example press a button. The control to submit the form should be set the CausesValidation attribute to true. In that case, when the button is pressed all validations are instantly executed. 
 
Now, we are going to take a look at some of these controls, the way we did in the previous chapter. So, what we want to ensure right now is:
  1. The Name is filled
  2.  The Email has proper email format.
  3. The next Textbox contains a number between 3 and 5.
  4. You must answer Yes on the Do you like DotNetHints? question.
  5. The Phone's format is numeric (validate using JavaScript).
  6. The Phone's format is numeric (validate using server side response).
 
form validation-aspnet-error
 
This is the aspx code we will use.
 
 
    ASP.NET Validation
 
    <table>
        <tr>
             <td>Name</td>
            <td><asp:TextBox runat="server" ID="NameBoxID"  /></td>
            <td><asp:RequiredFieldValidator ID="RequiredFieldValidatorID" runat="server" ControlToValidate="NameBoxID" 
                  Text="Name is required" SetFocusOnError="true"/></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><asp:TextBox runat="server" ID="MailBoxID"  /></td>
            <td><asp:RegularExpressionValidator  ID="RegularExpressionValidator1" runat="server"
                    ControlToValidate="MailBoxID" ValidationExpression=".*@.{2,}\..{2,}"
                    Text="E-mail is not in a valid format" SetFocusOnError="true"/></td>
        </tr>
        <tr>
            <td>Random number between 2 and 5</td>
            <td><asp:TextBox runat="server" ID="NumberBoxID" /></td>
            <td><asp:RangeValidator ID="RangeValidatorID" runat="server" ControlToValidate="NumberBoxID" 
                Type="Double"  MinimumValue="2" MaximumValue="5" Text="Wrong number!" SetFocusOnError="true"/></td>
        </tr>
        <tr>
            <td>Do you like DotNetHints?</td>
            <td><asp:TextBox runat="server" ID="DotNetHintsBoxID" /></td>
            <td><asp:CompareValidator ID="CompareValidatorID" runat="server" ControlToValidate="DotNetHintsBoxID"
                  Text="You must answer Yes" ValueToCompare="Yes" SetFocusOnError="true"/></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td><asp:TextBox runat="server" ID="PhoneBoxID" /></td>
            <td><asp:CustomValidator ID="CustomValidatorID" runat="server" ControlToValidate="PhoneBoxID"
                ClientValidationFunction="checkNumberASPNET" Text="Not a phone number format" SetFocusOnError="true"/></td>
        </tr>
        <tr>
            <td>Phone (Server Validation)</td>
            <td><asp:TextBox runat="server" ID="PhoneBoxIDServerValidationID" /></td>
            <<td><asp:CustomValidator ID="CustomValidatorServerID" runat="server" ControlToValidate="PhoneBoxIDServerValidationID"
                 OnServerValidate="CheckNumberOnServer" Text="Not a phone number format" SetFocusOnError="true"/></td>
        </tr>
        <tr><td><asp:Button  runat="server" ID="SubmitBtnID" Text="Submit" OnClick="SubmitButtonClicked" CausesValidation="true" /></td></tr>
    </table>
 
 
The first and simplest validator to encounter is the RequiredFieldValidator, which we will set to look upon the NameBoxID TextBox. This validator fails in case the NameBoxID is empty. That's all.
 
Next is the RegularExpressionValidator which we will use to validate the email set in the MailBoxID TextBox. Remember the regular expression we used in the previous chapter? We are going to use it here as well. All it takes is to set it to the ValidationExpression attribute. ValidationExpression=".*@.{2,}\..{2,}"
 
Now, we need to ensure the NumberBoxID gets no number less than 2 or greater than 5. To do so, we will use a RangeValidator. We should set Type to Double (integer may do as well) and its MinimumValue and MaximumValue to 2 and 5 respectively.
 
"Do you like DotNetHints?" should get nothing but "Yes" as an answer. A CompareValidator will do just fine. All we need is to set the expected value to the ValueToCompare attribute.
 
So far, we have easily accomplished quite a few things. How about creating some custom validation of our own? In that case we have to use a CustomValidator. This validator helps as create a JavaScript function or a code behind method to validate. Let's do the JavaScript part first.
 
We are using the attribute ClientValidationFunction and set its value to "checkNumberASPNET". This is the name of the JavaScript function we are calling. The function will use regular expressions to do about the same thing as before.
 
 function checkNumberASPNET(ctl, args) {
            
            var numberRegEx = /^\d+$/;
            var number = args.Value;
 
            if (!number.match(numberRegEx)) 
                args.IsValid = false;
            else 
                args.IsValid = true;
        } 
 
The function contains two arguments. First argument is the validation control. Second argument is the control to be validated. Using the Value attribute, we get the value we want to check. If the validation fails. we should set the IsValid attribute to false.
 
However we can choose to do the same thing using postback. Simply set the OnServerValidate attribute to the name of the validation method. This will be CheckNumberOnServer in our case.
 
The method to be executed (we are using C# in this example) should be declared protected and return void and contain an object and a ServerValidateEventArgs attribute, much like any server side event method call would look like. Just so, we don't use regular expressions once again, we may use the TryParse method. If validation is valid we set args.IsValid to true, otherwise it should be false.
 
This is how our method looks like
 
protected void CheckNumberOnServer(object sender, ServerValidateEventArgs args)
    {
        int phoneNumber;
        args.IsValid = Int32.TryParse(PhoneBoxIDServerValidationID.Text, out phoneNumber);
    }
 
 These should be enough in order to create your first form validations. Keep in mind that client side validation is not always secure. So when the button is pressed and, even if all validators return true, you should create a final overall validation just before you use the data you are given.
 
 
 

Validating emails using .Net

There is also another way we can check if an email is valid. That is by allowing .Net to do the validation. 
 
We will use the System.Net.Mail.MailAddress class. There is a constructor that takes an email address as a string argument. If that email address is valid then the email will be created. If the email address is not valid we will get an exception stating that "The specified string is not in the form required for an e-mail address." Using this method we do not have to deal with regular expressions ourselves. .Net does all the nasty job.
 
Here's an example 
 
//Check if email address is valid using .Net
string email;
 
        try
        {
            email = (new System.Net.Mail.MailAddress("kostas@dotnethints.com")).Address.ToString();
        }
        catch
        {
        }
 
 

 Captcha

 You have probably seen captcha as you surf the web, even though you may not know how it is called. It is the control that shows you a few characters within a blurry twisted image that is difficult to be recognized by image processing techniques, but are however easily (supposed so) read by a human being. If the characters you insert in the box do not match the ones shown you may not submit the form. 
 
 
recaptcha
 
 
 Why do we use captcha? Captcha can tell the difference between the man and computer. This way we ensure that human beings alone insert data in our form. You see, there may be scripts out there that fill in the data they contain in your form and submit it. However we obviously do not want to get data that is not actual, so we have to stop it. And that's why we will use captcha.
 
 .Net does not include captcha controls. They are third party controls, so we have to search for them online and find them. There are many type of captchas out there for you to use. We will see how to use recaptcha, the captcha suggested by google, as an example.
 
 
 To use recaptcha, first thing to do, is to download the necessary files. You may use this link.
 
 Then, you have to register your website here so you can get a public and private key. Make sure you fill in your actual website, otherwise the control will not work.
 
Next you have to add a reference to your website. This can be done by right clicking on your project on the Solution Explorer and click Add Reference... Spot the downloaded dll and you are right on your way.
 
We're almost done. Go to the aspx page you wish to insert the recaptcha control and set 
<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>
on top. Then all you have to do is place this control
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" PublicKey="My_Public_Key" PrivateKey="My_Private_Key" />
wherever you want. PublicKey and PrivateKey should be the keys you were given when registering your site.
 
When you get a request you should check for the Page.IsValid value. If it is set to false, recaptcha validation has failed. If not you are ready to go on.
 
 

Summary

When submitting forms you should always validate the input. This can be done using client or server side validation. Client side is faster and easier but may be bypassed so you have to use server side validation as well. You can validate using JavaScript or ASP.NET's validation controls. To ensure that the person inserting data is real, you should use captcha.

Back to BlogPreviousNext

Comments



    Leave a comment
    Name: