65.9K
CodeProject is changing. Read more.
Home

Creating Custom Required Field Validator Control that inherits the Syste.Web.UI.WebControls.RequiredFieldValidator control

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (6 votes)

Dec 12, 2006

2 min read

viewsIcon

38568

The control that is created is used to validate textbox and on error it indicates the validated textbox with changed background color for better user interface

Introduction

Here I am presenting the custom web control that is used to validate the textbox values same as RequiredFieldValidator control of ASP.NET. As, I am developing asp.net application I have to validate the input values at client side and also at server side and also at the time of error I need to indicate the textbox with changed background color. This required facility is not provided by the RequiredFieldValidator control of ASP.NET. So, I developed a custom Required Field Validator control that does this work and also it inherits the RequiredFieldValidator control of ASP.NET

Features

This control provides the ability of highlighting the textbox at time of error with changed background color. It also provide the facility of checkin the length of the input value for the given defined value at the time of development.

Limitations

This control only validates the textboxes. Also, this control does not provide facility of validating reqular expressions like email or internet url.

How the control is developed

For developing this control I have used Web Control Library project and the language C# 2.0.

To develope this control I have inhireted the RequiredFieldValidatorControl as my custom controls base class and overrided few methods. I have overrided OnPreRender,OnInit and EvaludateIsValid methods. I have also created custom properties like OriginalErrorMessage,MaximumTextLength,MaximumTextLengthErrorMessage,OriginalBackcolor,TextBoxBackgroundColorOnError. Short description of each property is as follows:

1)OriginalErrorMessage: this property provides the original error messgae

2)MaximumTextLength: this property is used to check if user input exceed the required lenght or not (by default this property is set to 0 means no length check)

3)MaximumTextLengthErrorMessage:this property is used to store the error message which is displayed at time of MaximumTextLength validation fails.

4)OriginalBackColor:This property is used to set the original background color of the textbox when no error is occured.

5) TextBoxBackgroundColorOnError: This property is used for setting the validated textbox background color at the time of error.

In the OnPerRender method I am injecting the javascript for client side validation and also it sets the background color of textbox if error is occured. The name of validating function is RequiredFieldValidatorEvaluateIsValid which is the default when the RequiredFieldValidator control of ASP.NET is rendered.

In OnInit method I am getting the textbox that is going to be validated and also getting its default background color for setting it when there is no error.

Complete Code for the control



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomWebControlsLibrary
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomRequiredFieldValidatorControl
runat=server></{0}:CustomRequiredFieldValidatorControl>")]
public class CustomRequiredFieldValidatorControl : RequiredFieldValidator
{

[Category("
Behavior")]
[Description("
Get or set the value of Maximum Text Length.")]
public int MaximumTextLength
{
get {
if (ViewState["
MaximumTextLength"] != null)
{
return int.Parse(ViewState["
MaximumTextLength"].ToString());
}
else {
return 0;
}
}
set {
ViewState["
MaximumTextLength"] = value;
}
}
        
        public Color TextBoxBackgroundColorOnError
{
get {
if (ViewState["TextBoxBackgroundColorOnError"] != null)
{
return (Color)ViewState["TextBoxBackgroundColorOnError"];
}
else {
return System.Drawing.Color.LightGray;
}
}
set {
ViewState["TextBoxBackgroundColorOnError"] = value;
}
}
        private string OriginalErrorMessage
{
get {
if (ViewState["OriginalErrorMessage"] != null)
{
return (string)ViewState["OriginalErrorMessage"];
}
else {
return "Provide valid Value";
}
}
set {
ViewState["OriginalErrorMessage"] = value;
}
}
        
private Color OriginalBackgroundColor
{
get {
if (ViewState["OriginalBackgroundColor"] != null)
{
return (Color)ViewState["OriginalBackgroundColor"];
}
else
return Color.LightGray;
}
set {
ViewState["OriginalBackgroundColor"] = value;
}
}
        public string MaximumTextLengthErrorMessage
{
get {
if (ViewState["MaximumTextLengthErrorMessage"] != null)
{
return (string)ViewState["MaximumTextLengthErrorMessage"];
}
else {
return "Please enter valid value.";
}
}
set {
ViewState["MaximumTextLengthErrorMessage"] = value;
}
}
private bool IsOriginalBackColorSet
{
get {
if (ViewState["IsOriginalBackColorSet"] != null)
{
return (bool)ViewState["IsOriginalBackColorSet"];
}
else {
return false;
}
}
set {
ViewState["IsOriginalBackColorSet"] = value;
}
}
TextBox textBox = new TextBox();
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
textBox = ((TextBox)(Page.FindControl(base.ControlToValidate)));
if (!IsOriginalBackColorSet)
{
OriginalErrorMessage = base.ErrorMessage;
OriginalBackgroundColor = textBox.BackColor;
IsOriginalBackColorSet = true;
}

}
        protected override bool EvaluateIsValid()
{
string Value = base.GetControlValidationValue(base.ControlToValidate);
if (Value == "")
{
textBox.BackColor = TextBoxBackgroundColorOnError;
return false;
}
else if (MaximumTextLength > 0)
{
if (Value.Length > MaximumTextLength)
{
textBox.BackColor = TextBoxBackgroundColorOnError;
ErrorMessage = MaximumTextLengthErrorMessage;
return false;
}
else {
textBox.BackColor = OriginalBackgroundColor;
}
}
else {
textBox.BackColor = OriginalBackgroundColor;
}
return true;
}
        protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string validatedcontrolclientid = base.GetControlRenderID(base.ControlToValidate);
string script = @"<script language="'javascript'">
function RequiredFieldValidatorEvaluateIsValid(val){
var value = ValidatorGetValue(val.controltovalidate);
if(value == '')
{
document.getElementById('"
+ validatedcontrolclientid + "').style.backgroundColor='" +
ColorTranslator.ToHtml(TextBoxBackgroundColorOnError) + "';";
script += "document.getElementById('" + base.ClientID + "').innerHTML='" + OriginalErrorMessage +
"';";
script+="return false;}";
script += "else{document.getElementById('" + validatedcontrolclientid + "').style.backgroundColor='" +
ColorTranslator.ToHtml( OriginalBackgroundColor) + "';return true;}}</script>";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidationScript", script);
}
}
}


Please let me know about any error or any bug in my code.

How to use the Code

To use this code just create a Web Control Library project. Paste the entire code from here and build the application and take the referrence of the created .dll file to you project to use this control.

Validating for fixed length set the property MaximumTextLength to required value and also set the MaximumTextLengthErrorMessage. You can also set the TextBoxBackgroundColorOnError. Otherwise the default value of "LightGary" color is returnred.