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>