Click here to Skip to main content
15,885,117 members
Articles / Web Development / ASP.NET
Article

NumericValidator Control for ASP.Net

Rate me:
Please Sign up or sign in to vote.
3.57/5 (3 votes)
13 Nov 20072 min read 32.2K   326   17   7
Numeric Validator is one control that performs required field, decimal and range validation
Screenshot - ClassDiagram-NumericValidator.gif

Introduction

Validation controls available in .Net Framework solves almost all the basic validation needs of the application. Complex validations needs can be achieved by combining two or more validation control provided. One such validation is Textbox control dealing with numerics. Numeric validation comprises of following things.

1. Required Field validation
2. Decimal places validation
3. Range validation

Whenever an application needs this functionality, developer needs to work with above mentioned validator controls for every textbox control. To avoid the repetitive work, I came up with a control which performs all these validation in one control.

Validation inside the control is performed using javascript. Most important thing is I am using the existing javascript methods available inside the .Net Framework - so "No reinventing of wheels". But, logic of handling the methods is mine.

Background

I am involved in projects which provide Banking solutions. Most of the time I deal with Textbox and Numeric validation. I found myself doing the same repetitive validation which is time consuming. As a result, I combined some regular numeric validation and made it into a single control.

Description of NumericValidator control

As explained earlier, NumericValidator control is derived from CustomValidator class. It has the following properties. AllowDecimalErrorMessage - Message to displayed in a ValidationSummary when the validated control have decimal values.
RangeValidationErrorMessage - Message to displayed in a ValidationSummary when the validated control value doesnt fall under the Maximum and Minimum Range specified.
MaximumValue - Maximum value for the control being validated.
MinimumValue - Minimum value for the control being validated.
InitialValue - Initial value of the field to validate.
AllowDecimal - Indicates whether the control to be validated allows Decimal.
RequiredFieldErrorMessage - Message to displayed in a ValidationSummary when the validated control is empty.
RequiredFieldValidator - Indicated whether the control to be validated is checked for Required field.
DecimalValidator - Indicated whether the control to be validated for Decimal values.
EnableOnControlToValidateStatus - Validator Control enables only if Control To Validate is enabled

Logic implemented in the OnPreRender method to achieve the functionality

C#
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    script = new StringBuilder();
    base.ClientValidationFunction = "MaxNumericValidator";
    base.ValidateEmptyText = this.RequiredFieldValidator;

    if (!Page.ClientScript.IsClientScriptBlockRegistered("MaxNumericValidatorScript"))
    {
        script.Append("<script type=\"text/javascript\">\n");
        script.Append("function MaxNumericValidator(source, args)\n");
        script.Append("{\n");
        script.Append("\tif(source.enableOnControlToValidateStatus == \"True\")\n");
        script.Append("\t{\n");
        script.Append("\t\tif(document.all[source.controltovalidate].disabled == true)\n");
        script.Append("\t\t{\n");
        script.Append("\t\t\targs.IsValid = true;\n");
        script.Append("\t\t\treturn;\n");
        script.Append("\t\t}\n");
        script.Append("\t}\n");

        script.Append("\tvar value = ValidatorGetValue(source.controltovalidate);\n");
        script.Append("\tif(source.requiredfieldvalidator == \"True\")\n");
        script.Append("\t{\n");
        script.Append("\t\tif((ValidatorTrim(value) != ValidatorTrim(source.initialvalue)) == false)\n");
        script.Append("\t\t{\n");
        script.Append("\t\t\tsource.innerHTML = source.requiredfielderrormessage;\n");
        script.Append("\t\t\targs.IsValid = false;\n");
        script.Append("\t\t\treturn\n");
        script.Append("\t\t}\n");
        script.Append("\t}\n");

        script.Append("\tif (ValidatorTrim(value).length == 0)\n");
        script.Append("\t{\n");
        script.Append("\t\targs.IsValid = true;\n");
        script.Append("\t}\n");

        script.Append("\tvar strRegExp;\n");

        script.Append("\tif(source.decimalValidator == \"True\")\n");
        script.Append("\t{\n");
        script.Append("\t\tif(source.allowdecimal == 0)\n");
        script.Append("\t\t\tstrRegExp = " + @"""^[-+]?[0-9]\\d*"";" + "\n");
        script.Append("\t\telse\n");
        script.Append("\t\t\tstrRegExp = " + @"""^[-+]?[0-9]\\d*(\\.\\d{1,"" + source.allowdecimal + ""})?%?$"";" + "\n");
        script.Append("\t\tvar rx = new RegExp(strRegExp);\n");
        script.Append("\t\tvar matches = rx.exec(value);\n");
        script.Append("\t\tsource.innerHTML = source.allowdecimalerrormessage;\n");
        script.Append("\t\targs.IsValid = (matches != null && value == matches[0]);\n");
        script.Append("\t}\n");

        script.Append("\tif(args.IsValid == true && (source.maximumvalue != \"\" || source.minimumvalue != \"\"))\n");
        script.Append("\t{\n");
        script.Append("\t\tsource.innerHTML = source.rangevalidationerrormessage;\n");

        script.Append("\t\targs.IsValid = (ValidatorCompare(value, source.minimumvalue, \"GreaterThanEqual\", source) && \n");
        script.Append("\t\t\tValidatorCompare(value, source.maximumvalue, \"LessThanEqual\", source));\n");
        script.Append("\t}\n");
        script.Append("\tif(args.IsValid == true)\n");
        script.Append("\t{\n");
        script.Append("\t\tsource.innerHTML = \"\";\n");
        script.Append("\t}\n");

        script.Append("}\n");

        script.Append("</script>\n");
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MaxNumericValidatorScript", script.ToString());
    }

    script = new StringBuilder();

    if (!Page.ClientScript.IsStartupScriptRegistered(this.ClientID))
    {
        try
        {
            script.Append("<script type="\"text/javascript\""></script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, script.ToString());
        }
        catch (Exception exp)
        {
            this.Page.Response.Write(exp.Message);
            this.Page.Response.End();
        }
    }
}

Using the code

Add the control to your web application by adding the NumericValidator.dll to the toolbox. NumericValidator control will be displayed under Validation tab. Add a Textbox control, NumericValidator control and Button control to the web page.

Set controltovalidate property of NumericValidator control to name of the Textbox control. To achieve all requiredfield, rangevalidation(10-100) and decimal place validation(upto 2 decimal places), set the following properties and execute the application

AllowDecimal="2"
DecimalValidator="True"
MaximumValue="100"
MinimumValue="10"
RequiredFieldValidator="True"

HTML
<cc1:numericvalidator id="NumericValidator1" runat="server" controltovalidate="TextBox1" AllowDecimal="2" DecimalValidator="True" 
 MaximumValue="100" MinimumValue="10" RequiredFieldValidator="True"></cc1:numericvalidator>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
I am a web developer working in banking applications.

Comments and Discussions

 
GeneralExcellent Control Pin
vk1237726-May-09 3:59
vk1237726-May-09 3:59 
QuestionError with this control placed on UpdatePanel Pin
Sheikh Nabeel Moeen10-Mar-09 23:28
Sheikh Nabeel Moeen10-Mar-09 23:28 
GeneralSweet add-on Pin
Ricky Wang21-Nov-07 13:37
Ricky Wang21-Nov-07 13:37 
QuestionOnPrender method when dynamically created Pin
silverby20-Nov-07 3:02
silverby20-Nov-07 3:02 
Hi,

very nice control! I tried your control both by adding it during design time and as a dynamic control in the code behind. The problem that I ran into was that the OnPrerender method was not called when adding the control runtime. Why is that?

/Patrik
AnswerRe: OnPrender method when dynamically created Pin
Naveen Bharathi20-Nov-07 16:57
Naveen Bharathi20-Nov-07 16:57 
GeneralRe: OnPrender method when dynamically created Pin
silverby21-Nov-07 19:56
silverby21-Nov-07 19:56 
Generalthanks Pin
ronglj13-Nov-07 19:18
ronglj13-Nov-07 19:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.