Click here to Skip to main content
13,297,411 members (58,625 online)
Click here to Skip to main content
Add your own
alternative version


17 bookmarked
Posted 13 Nov 2007

NumericValidator Control for ASP.Net

, 13 Nov 2007
Rate this:
Please Sign up or sign in to vote.
Numeric Validator is one control that performs required field, decimal and range validation
Screenshot - ClassDiagram-NumericValidator.gif


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.


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

protected override void OnPreRender(EventArgs 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("\tif(source.enableOnControlToValidateStatus == \"True\")\n");
        script.Append("\t\tif(document.all[source.controltovalidate].disabled == true)\n");
        script.Append("\t\t\targs.IsValid = true;\n");

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

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

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

        script.Append("\tif(source.decimalValidator == \"True\")\n");
        script.Append("\t\tif(source.allowdecimal == 0)\n");
        script.Append("\t\t\tstrRegExp = " + @"""^[-+]?[0-9]\\d*"";" + "\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("\tif(args.IsValid == true && (source.maximumvalue != \"\" || source.minimumvalue != \"\"))\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("\tif(args.IsValid == true)\n");
        script.Append("\t\tsource.innerHTML = \"\";\n");


        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MaxNumericValidatorScript", script.ToString());

    script = new StringBuilder();

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

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


<cc1:numericvalidator id="NumericValidator1" runat="server" controltovalidate="TextBox1" AllowDecimal="2" DecimalValidator="True" 

 MaximumValue="100" MinimumValue="10" RequiredFieldValidator="True"></cc1:numericvalidator>


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


About the Author

Naveen Bharathi
Web Developer
United Kingdom United Kingdom
I am a web developer working in banking applications.

You may also be interested in...


Comments and Discussions

GeneralExcellent Control Pin
vk1237726-May-09 4:59
membervk1237726-May-09 4:59 
QuestionError with this control placed on UpdatePanel Pin
Sheikh Nabeel Moeen11-Mar-09 0:28
memberSheikh Nabeel Moeen11-Mar-09 0:28 
GeneralSweet add-on Pin
Aliasncnu21-Nov-07 14:37
memberAliasncnu21-Nov-07 14:37 
QuestionOnPrender method when dynamically created Pin
silverby20-Nov-07 4:02
membersilverby20-Nov-07 4:02 
AnswerRe: OnPrender method when dynamically created Pin
Naveen Bharathi20-Nov-07 17:57
memberNaveen Bharathi20-Nov-07 17:57 
GeneralRe: OnPrender method when dynamically created Pin
silverby21-Nov-07 20:56
membersilverby21-Nov-07 20:56 
Generalthanks Pin
ronglj13-Nov-07 20:18
memberronglj13-Nov-07 20: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 13 Nov 2007
Article Copyright 2007 by Naveen Bharathi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid