Click here to Skip to main content
Licence 
First Posted 13 Nov 2007
Views 16,094
Downloads 185
Bookmarked 17 times

NumericValidator Control for ASP.Net

By | 13 Nov 2007 | Article
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

        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"

<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

About the Author

Naveen Bharathi

Web Developer

United Kingdom United Kingdom

Member

I am a web developer working in banking applications.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralExcellent Control Pinmembervk123773:59 26 May '09  
QuestionError with this control placed on UpdatePanel PinmemberSheikh Nabeel Moeen23:28 10 Mar '09  
GeneralSweet add-on PinmemberAliasncnu13:37 21 Nov '07  
QuestionOnPrender method when dynamically created Pinmembersilverby3:02 20 Nov '07  
AnswerRe: OnPrender method when dynamically created PinmemberNaveen Bharathi16:57 20 Nov '07  
GeneralRe: OnPrender method when dynamically created Pinmembersilverby19:56 21 Nov '07  
Generalthanks Pinmemberronglj19:18 13 Nov '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web04 | 2.5.120517.1 | Last Updated 13 Nov 2007
Article Copyright 2007 by Naveen Bharathi
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid