Skip to main content

Validation in ASP.NET 2.0



Validation server controls are set of controls that enable you to work with the information your end users inputs into application. Application should always ensure that valid data is recorded. To ensure valid data is collected, we apply set of validations to data we collect. Validation is a set of rules that you apply to the data you collect. In this way, we can bring certain degree of discipline in end user.

We can understand validation under two categories: Client side validation and Server side validation. Client side validation involves validating user input before the page is posted to server. Server side validation involves performing checks on server instead of client. This is most secure form but comes at cost of performance.
ASP.NET introduced smart validation server controls to implement page level validations. They are capable of performing both server side and client side validations. So, Validation server controls offer the combined power of both approaches such that the security of application is never compromised.

ASP.NET 2.0 Validation server controls

Presently, ASP.NET 2.0 offers six validation controls. It also added new features like Validation groups and new JavaScript capabilities.
  • RequiredFieldValidator
  • CompareValidator
  • RangeValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary

Validation Properties

Usually, Validation is invoked in response to user actions like clicking submit button or entering data. Suppose, you wish to perform validation on page when user clicks submit button. To make this happen, simply set the CauseValidation property to True for submit button as shown below
<asp:Button ID="Button1" runat="server" Text="Submit" CausesValidation=true />

RequiredFieldValidator

The RequiredFieldValidator control is simple validation control which checks to see if the data is entered for the attached control. You can have a RequiredFieldValidator control for each form element on which you wish to enforce Mandatory Field rule.
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ErrorMessage="Required!" ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" Text="Submit" CausesValidation="true"/>
    </div>
    </form>

RequiredFieldValidator
As shown in above output, RequiredFieldValidator control ensures that you enter data in textbox before you click submit button. You can throw appropriate error message if the validation fails. You can set error message using ErrorMessage property and control to validate using ControltoValidate property. Similarly, you can use InitialValue property to control the initial value of attached control.
 

CompareValidator Server Control

The CompareValidator control allows you to make comparisons between two form elements as well as to compare values contained with in form element to constants that you specify. For instance, you can specify that a form's element value must be an integer and greater than a specified number.
<td>
            <asp:TextBox ID="TextBox2"  TextMode="Password" runat="server"></asp:TextBox>
        </td>
        </tr>
        <tr>
        <td>
        <asp:Label ID="Label2" runat="server" Text="Confirm Password"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="TextBox3" TextMode="password" runat="server"></asp:TextBox>
        </td>
        <td>
        <asp:Button ID="Button2" runat="server" Text="Login"/>
        </td>
        </tr>
        </table>
        <asp:CompareValidator ID="CompareValidator1" runat="server"ErrorMessage="Passwords don't match!" ControlToValidate="TextBox3" 
        ControlToCompare="textbox2" ></asp:CompareValidator>

CompareFieldValidator
As shown in above output, you can see that ComparisonValidator makes comparisons between two form elements. You can see that Enter password textbox value is matched against Confirm Password textbox values to make sure that they match. If they don't match in their values, you can display error message by setting ErrorMessage property as shown above. In above example, we need only a single CompareValidator control on the page because a single comparison is made. Therefore, you use the ControlToCompare property. This specifies what value is compared to Textbox2. In this case, the value is Textbox3.

RangeValidator Server Control

The RangeValidator Server Control makes sure that the end user value or selection provided is between a specified ranges. Below given example should give you clear picture.
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Value must be between 20 and 30" ControlToValidate="RangeTextbox" 
        Type="Integer" MinimumValue="20" MaximumValue="30" >
        </asp:RangeValidator>
        <asp:TextBox ID="RangeTextbox" runat="server"></asp:TextBox>
        <asp:Button ID="CheckRange" runat="CheckRange" Text="Button" />

RangeValidator
In above example, you might observe that we are using RangeValidator control to see that valid values in the specified range are entered. We can use MinimumValue and MaximumValue property to set the beginning and ending range values. I have entered 55 which did not fall under given range, so validation fails giving out this error message. You can use RangeValidator not only for validating numbers but also about validating a range of string characters, calendar dates. You can use Type property to specify the type of range.

RegularExpressionValidator Server Control

Using RegularExpressionValidator server control, you can check a user's input based on a pattern that you define using a regular expression. This means that you can define a structure that a user's input will be applied against to see if its structure matches the one that you define.
 <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="Textbox4" runat="server" 
        ErrorMessage="You must enter an email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>
        <asp:Button ID="Button3" runat="server" Text="CheckMail"/>

RegularExpressionValidator
As indicated above, we are using RegularExpressionValidator to define the structure of input to be entered in above textbox. You can specify the pattern for RegularExpressionValidator using ValidationExpression property. ASP.NET 2.0 provides predefined set of universal patterns (Regular Expressions) to choose from through Regular Expression Editor. To see Regular Expression Editor in action, switch to Design mode. Open RegularExpressionValidator control in Design View. From Properties dialog box, click button next to ValidationExpression Property. You can see below given Regular Expression Editor window

Regular Expression Editor

CustomValidator Server Control

Sometimes, predefined Validation controls cannot address some of our critical requirements. You have to go beyond what they offer. This is where the CustomValidator control comes into play. The CustomValidator control allows you to build your own client-side or server-side validations that can then be easily applied to your web forms. Let's see an example where you require a number that is divisible by 6. We use CustomValidator control to perform a custom client-side validation on the user input to make sure that the number provided is divisible by 6.
<asp:CustomValidator ID="CustomValidator1" runat="server" 
        ControlToValidate="textbox5" ClientValidationFunction="validatenumber" 
        ErrorMessage="Number is not divisible by 6"></asp:CustomValidator>
        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
        <asp:Button ID="Button4" runat="server" Text="Divisible" />
 
<script type="text/javascript">
function validatenumber(oSrc,args)
{
args.IsValid = (args.Value % 6 == 0)
}
</script>

CustomValidator
As shown above, we are using custom JavaScript. This is the script we want the CustomValidator control to use when making its validation checks on the information entered into the textbox. The JavaScript functions you employ are going to use the args.IsValid property and set this property to either true or false depending on the outcome of the validation check. In this case, the user input (args.Value) is checked to see if it is divisible by 6. The Boolean value returned is then assigned to the args.IsValid property, which is then used by the CustomValidator control. We use ClientValidationFunction property to set the name of the client-side function that you want this validation check to employ when the CustomValidator control is triggered. In this case, it is validatenumber function as shown above.

ValidationSummary Server Control

The ValidationSummary control is reporting control, which is used by the other validation controls on a page. You can use this validation control to consolidate errors reporting for all the validation errors that occur on a page instead of leaving this up to each and every individual validation control.
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"  HeaderText="You received following errors" runat="server" />

ValidationSummary control
From above output, you might understand that ValidationSummary control simply displays all the Validation errors at one location. DisplayMode decides the mode of display like displaying the results in bulleted list or simple list as shown above. As in earlier examples, these validation errors appear next to each of the textboxes. You can see, however, that the ValidationSummary control also displays the validation errors as bulleted list in red at the location of the control on form. In most cases, you do not want these errors to appear twice on a page for the end user. You can change this behavior by using Text property of the validation controls, in addition to ErrorMessage property as shown below.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" Text="*" ControlToValidate="Textbox4" runat="server" 
        ErrorMessage="You must enter an email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>

ValidationSummaryControl
Now you can see that error message for RegularExpressValidator is displayed in ValidationSummary control instead of RegularExpressionValidator control.

Validation Groups


Validation Groups
You might observe in above figure that u could see two error messages. Though, I clicked Divisible button to look for Customvalidator control, the RequiredFieldvalidator is also fired. Since textbox is empty, you can see error for RequiredFieldValidator. If there are multiple validation controls on the page and you do not want all the Validation controls to fire together. You just want them to fire only when certain condition is met.
ASP.NET 2.0 now provides you with a ValidationGroup property that enables you to separate the validation controls into separate groups. It enables you to activate only the required validation controls when an end user clicks a button on the page. To achieve this, you can set the ValidationGroup property for each validation control. The core server controls have the ValidationGroup property because things like button clicks must be associated with specific validation groups.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ValidationGroup="Submit" ErrorMessage="Required!" ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" ValidationGroup="Submit" Text="Submit"/>

Validation Groups
Now you can see that you could see only one error message specific to CustomValidator control. You don't see any RequiredFieldValidator related messages. This is made possible by assigning RequiredFieldValidator controls to different ValidationGroup called submit. Now RequiredFieldValidator will be fired only when Submit button is clicked.

Comments

Popular posts from this blog

C# Generic class to parse value - "GenericConverter"

    public class GenericConverter     {         public static T Parse<T>(string sourceValue) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T));         }         public static T Parse<T>(string sourceValue, IFormatProvider provider) where T : IConvertible         {             return (T)Convert.ChangeType(sourceValue, typeof(T), provider);         }     }     public static class TConverter     {         public static T ChangeType<T>(object value)         {             return (T)ChangeType(typeof(T), value);         }         public static object ChangeType(Type t, object value)         {             TypeConverter tc = TypeDescriptor.GetConverter(t);             return tc.ConvertFrom(value);         }         public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter         {             TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));         }     } ----------------

How to create a countdown timer in jquery

Create a countdown timer in jQuery First we need to include the jQuery library file to the HTML page to perform this task. To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery. We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy. As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag. Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;” Now we need to put the condition if timer got finished (if (t

Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site. This blog post covers how you can use the free Microsoft  URL Rewrite Extension  to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple  URL Rewrite  rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content). [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at:  twitter.com/scottg