Thursday, March 8, 2012

Another good Example Custom validator with Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UsingCustomValidator" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Using a CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
   
    Enter a date:<br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="custDate" runat="server"
       ControlToValidate="txtDate"
       ValidateEmptyText="false"
       Text="Enter a valid future date"
       OnServerValidate="custDate_ServerValidate" />  
   

   <script type="text/javascript">
     function validateOrFields(source, args){
       var sUser = document.form1.<%= txtUser.ClientID %>.value;
       var sEmail = document.form1.<%= txtEmail.ClientID %>.value;
     
       if (sUser == "" && sEmail == "")
       {
          args.IsValid = false;
       }
       else
       {
          args.IsValid = true;
       }
       return;
     }
   </script>
 
   Enter user name:<br />
   <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
   <br />
   Enter email:<br />
   <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

   <asp:CustomValidator ID="OrFieldValidator"
                        runat="server"
                        Text="Enter either a user name or a email"
                        ClientValidationFunction="validateOrFields"
                        OnServerValidate="OrFieldValidator_ServerValidate" />  
 

 
   <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
 
   </form>
</body>
</html>
<script type="text/javascript">
  ValidatorHookupControlID("<%= txtUser.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
  ValidatorHookupControlID("<%= txtEmail.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
</script>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UsingCustomValidator : System.Web.UI.Page
{
   protected void custDate_ServerValidate(object source, ServerValidateEventArgs args)
   {
      string sEnteredDate = args.Value;
      DateTime dt;
      bool convertSuccessful = DateTime.TryParse(sEnteredDate, out dt);
      if (convertSuccessful && dt >= DateTime.Today)
         args.IsValid = true;
      else
         args.IsValid = false;
   }

   protected void OrFieldValidator_ServerValidate(object source, ServerValidateEventArgs args)
   {
      if (txtUser.Text.Length <= 0 && txtEmail.Text.Length <= 0)
         args.IsValid = false;
      else
         args.IsValid = true;
   }
}

Introduction

This article shows how to use CustomValidator validation control that is available in ASP.NET out of the box.

Introduction
CustomValidator control is used to validate a input control with user-defined function either from server side or client side. Generally this control is used when you feel that no other validation controls provided out of the box in asp.net fit in your requirement. The interesting stuff in this control is that you have ability to validate your input data both from Client side using JavaScript and Server side by writing your code in code behind file in any of the .NET supported programming language.

The basic tutorials about this control had been written by me long back that is available here. In this article, we shall try to dig more into this control.

In order to explain this, I have taken a simple example of validating a TextBox for its length of characters through JavaScript at client side and validating the input for a valid email id through code behind in Server side.

Creating a Simple Form
Drag and drop a TextBox, Button and a Custom Validator control from the toolbar or you may prefer copying below code into your page as well to see how this control works.

<h3>Custom Validator</h3>
<asp:TextBox ID="txtEmail" AutoCompleteType="None" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CV1" runat="Server" ClientValidationFunction="JSValidate"
OnServerValidate="ServerValidate" Text="At least 8 character long"
ControlToValidate="txtEmail" ValidateEmptyText="True" ErrorMessage="Validation Failed"></asp:CustomValidator>

<br />
<asp:Label ID="lblMessage" ForeColor="brown" runat="Server" EnableViewState="False" />
<br />
<asp:Label ID="lblError" ForeColor="red" runat="Server" EnableViewState="False" />
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitThisForm" />
</p>



Notice the CustomValidator control here and focus on two properties called ClientValidationFunction and OnServerValidate. As their name suggests, the first one is to validate the input value of the TextBox from client side (JSValidate function) and other is to validate the input value from server side (ServerValidate method).

Lets see code for both functions here.

Client Side Function
When the Submit button will be clicked, first ClientValidationFunction function will fire that will try to validate the length of the characters entered into the TextBox, refer to the code below.

<script language="javascript" type="text/javascript">
function JSValidate(source, args)
{
var element = document.getElementById('<%=txtEmail.ClientID %>');

if (element.value.length >= 8) // you can also write args.Value
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
Note: It is important to maintain the definition of the function both at client side and server side. You can notice that above function has two parameter called source and args. As we are worried about the TextBox value here so first we need to get the id of the TextBox, I have got it using ClientID property of the TextBox control and have stored into the element variable. In the following line I am checking the length of the TextBox to see if its more than 8 characters and setting the value of IsValid property of the args parameter to true / false.

Setting the IsValid property of args tells the Validator function whether the client side validation has failed or passed. If failed, it will show the error Text specified in the CustomValidator control and will not submit the form else the form will be submitted to the server.

Get solutions of .NET problems with video explanations, .pdf and source code in .NET How to's.

Server Side Function
Once the client side validation has passed, Server side validation function ie. ServerValidate will fire. In this method, I am checking the TextBox value against the regular expression and if it is valid then assigning the value of IsValid property of the args parameter to true else false. Notice the signature of the Server Side method, this is same as the JavaScript function we uesd to validate in the client side.

protected void ServerValidate(object source, ServerValidateEventArgs args)
{
RegexStringValidator r = new RegexStringValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
try
{
r.Validate(args.Value);
args.IsValid = true;
}
catch (ArgumentException ee)
{
lblError.Text = "Error occured: Doesn't seem to be valid email id. <br />" +
ee.Message.ToString();
args.IsValid = false;
}
}

protected void SubmitThisForm(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblMessage.Text = "Success: The TextBox value is: <b>" + txtEmail.Text + "</b>";
}
}
Irrespective of the result of the Server side validation method, the onclick event of the Submit button will fire. To avoid processing the form in the OnClick event in case of Server side validation failed, we need to check for the validity of the page by using Page.IsValid, this ensures that all validation control placed in the .aspx page has passed successfully. If Page.IsValid returns true then we can go ahead with the processing of the form as shown in the SubmitThisForm method.


Hope this simple and basic article will help beginners to know how to use CustomValidator controls in ASP.NET web forms. please subscribe for the subsequent article alert directly in your email box. Thanks and Happy coding!

Tips for Validation Controls

Tip 1: Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.

Tip 2: The display property for the ASP.NET validation controls has 3 settings: None, Static(default), and Dynamic. ‘Static’ outputs HTML code (related to error) at all times even when no error has occurred. So when there is more than one validation control placed next to the field, the first validation control occupies screen space even when there is no error. In case the second validation control fires an error message, the message is pushed away from the control since the first validation control is occupying screen space.
Set the ‘display’ property of a validation control to ‘Dynamic’. This property renders the error message with the attribute display:none; It helps you to display the error message next to the control .

Tip 3: To prevent validation to occur on the click of the Cancel button, set the ‘CausesValidation’ property to false
<asp:Button ID=”btnCancel” Runat=”server” CausesValidation=”False” Text=”Cancel” />

Tip 4: Use the ‘InitialValue’ property of the RequiredFieldValidator to validate controls like combobox which have a default value.
For eg: If your combobox has a default item called “–Select –“ and you want that the user should select a value other than the default value before submitting the form, then set the ‘InitialValue’ property of the RequiredFieldValidator to “–Select–“.
<noscript><asp:DropDownList ID=”DropDownList1″ runat=”server”>
<asp:ListItem Value=”–Select–” />
<asp:ListItem Value=”Item1″ />
<asp:ListItem Value=”Item2″ />
<asp:ListItem Value=”Item3″ />
</asp:DropDownList>
<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ErrorMessage=”RequiredFieldValidator” ControlToValidate=”DropDownList1″ InitialValue=”–Select–”></asp:RequiredFieldValidator>

Tip 5: A RegularExpressionValidator can be used to handle string patterns. For eg: A Name textbox that should accept a maximum of 30 characters with only alphabets, space, fullstop(.) and a ‘(apostrophe). A regularexpression like ‘^([a-zA-z.'\s]{2,30})$’ does the trick.
However when you are using Localization and using a language like Arabic, you have to often provide for validating characters in a different dialect. You can solve this using the following technique:
- In the Resource.resx file, create a resourcekey called ValidName giving it a value of ^([a-zA-z.'\s]{2,30})$
- In the Resource.ar-EG.resx file, use the same key but with a diff value ^([\u0600-\u06FF.'\s]{2,30})$
Use it in your page using the following way. Observe the bold text:

<asp:RegularExpressionValidatorID=’regEVFname’ runat=’server’ControlToValidate=’txtName’
Display=’Dynamic’ErrorMessage=’Invalid’
ValidationExpression=’<%$ Resources:Resource, ValidName %>’SetFocusOnError=’True’></asp:RegularExpressionValidator>

When the user selects English, he can enter only A-Za-z. Similarly for Arabic, he can enter only the Arabic characters and not English.

Tip 6: The validation controls provide both Server and Client Side validation. To turn off client-side validation, set the ‘EnableClientScript = false’
<asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ Runat=”server”
Text=”Error” ControlToValidate=”TextBox1″ EnableClientScript=”false”/>

Tip 7: Use CompareValidator to validate date with format of “dd/MM/yyyy”.
The validator uses the CultureInfo object of the thread to determine date format. So what you need to do is to set the desired culture format in the Page directive
<%@ Page culture=”your culture” %>
This tip was shared by PeterBlum in the asp.net forums. By the way, Peter has an amazing suite of data entry and validation controls on his site at a reasonable price.

Tip 8: Instead of the textual error message, you can even add an image or sound to your validator control. The Text and Error Message property accepts HTML tags.
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<br />
<asp:RequiredFieldValidator ControlToValidate=”TextBox1″ EnableClientScript=”false” ID=”RequiredFieldValidator1″ runat=”server” Text=”<bgsound src=’C:\Windows\Media\Windows Error.wav’>”></asp:RequiredFieldValidator>
Just make sure that the EnableClientScript=”false” when you want a sound instead of a text message.

Tip 9: If you have two set of forms (eg: Login and Registration) in a single page and want to keep the validation of the two groups separate, use ‘ValidationGroups’. All you need to do, is to specify a common group name for a set of controls that you want to validate separately.
<div>
<asp:TextBox ID=”TextBox1″ ValidationGroup=”Group1″ runat=”server”></asp:TextBox>
<br />
<asp:RequiredFieldValidator ControlToValidate=”TextBox1″ ValidationGroup=”Group1″ ID=”RequiredFieldValidator1″ runat=”server” Text=”Error”></asp:RequiredFieldValidator>
<asp:Button ID=”Button1″ runat=”server” ValidationGroup=”Group1″ Text=”Button” />
</div>
<br />
<br />
<div>
<asp:TextBox ID=”TextBox2″ ValidationGroup=”Group2″ runat=”server”></asp:TextBox>
<br />
<asp:RequiredFieldValidator ControlToValidate=”TextBox1″ ValidationGroup=”Group2″ EnableClientScript=”false” ID=”RequiredFieldValidator2″ runat=”server” Text=”Error”></asp:RequiredFieldValidator>
<asp:Button ID=”Button2″ runat=”server” ValidationGroup=”Group2″ Text=”Button” />
</div>

Tip 10: Other validator controls like CompareValidator, RangeValidator etc. do not provide a way to detect if the field is blank or required. The only way is to do this is to add a RequiredFieldValidator along with the other validator controls.
However one exception being the CustomValidator which provides a property called ‘ValidateEmptyText’. Just set it to true and it validates the field even if the user has kept the field blank.

Tip 11: If you want your validation error message to appear in the ‘ValidationSummary‘ control, then set the ‘ErrorMessage’ property on that validation control. Also, setting ‘ShowMessageBox = true’ on the ValidationSummary enables you to display a popup alert.

Tip 12: In order to create a CustomValidationControl you have to derive from the ‘BaseValidator’ class and implement the ‘EvaluateIsValid()’ method.

Tip 13: In case of an error, the validation controls allow you to set focus on a control in error using the ‘SetFocusOnError’ property.
<asp:RequiredFieldValidator SetFocusOnError=”true” ControlToValidate=”TextBox1″ ID=”RequiredFieldValidator1″ runat=”server” Text=”Error!!”></asp:RequiredFieldValidator>