Wednesday, December 31, 2008

Using CustomValidator control

Validator controls in asp.net are very much useful ,if we want to validate at the client side.The form will post back if all the validators return positive results.We have 5 types of validation controls available.

  1. RequiredFieldValidator : Ensures that the associated control has been filled with user input.
  2. CompareValidator : If we want to compare values in 2 textboxes,we can use them.
  3. RangeValidator : Checks if the entered value is in the specified range,If so allows postback.
  4. RegularExpressionValidator:Validates the entered data against given regular expression
  5. CustomValidator : This is used when the built-in validators are insufficient to meet our requirement.

Creating CustomValidator

The validation logic is written as a javascript function which accepts 2 arguements.

One is the object and other is the context of validation.

The Name of the javascript function is given in the ClientValidationFunction property of the CustomValidator.

Example

Consider the scenario of getting a no which should be a multiple of 10, the existing validators are insufficient.Here we use our custom validator.

<asp:CustomValidator ID="CustomValidator1" runat="server" 
ClientValidationFunction="Validate" ControlToValidate="TextBox1"
ErrorMessage="No must be multiple of 10"></asp:CustomValidator>


The Javascript function written as


function Validate(object, context) {
if (context.Value%10 == 0) {
context.IsValid = true;
}
else {
context.IsValid = false;
}
}


Wish a very Happy & prosperous new year..

1 comment:

Blogger said...

If you need your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (even if they're dating somebody else now) you must watch this video
right away...

(VIDEO) Want your ex CRAWLING back to you...?