Almost evey TextBox input is going to be stored in Database (if it is not based on XML). In the DB we need to define a maximum length for any characters field, so, we need to be sure that the input text in the TextBox in not longer then the maximum defined length in the DB where it going to be stored.
We all use Validators. I don't understand why MS didn't include in the built in controls a simple length validator (yes, I know it can be done by the RegularExpressionValidator, but why complicate things?) that simply validate maximum or minimum length of input text. Luckly, creating our custom validation control is much simplier then it sound. All we need to do is a class that inhirite from CustomValidator, override some methods, add some properties, create a JavaScript validation method, compile it into DLL and use it as any other Validator.
Override the ControlPropertiesValid() method:
private TextBox _textBox;
/// <summary>
/// Check if the control is valid for validation
/// </summary>
/// <returns></returns>
protectedoverridebool ControlPropertiesValid()
{
Control ctrl = FindControl(ControlToValidate);
if (ctrl != null)
{
_textBox = ctrl as TextBox;
return (_textBox != null);
}
else
returnfalse;
}
override the EvaluateIsValid() method:
/// <summary>
/// Perform the validation
/// </summary>
/// <returns></returns>
protectedoverridebool EvaluateIsValid()
{
if ( string.IsNullOrEmpty(_textBox.Text) )
{
if (MinLength > 0)
returnfalse;
else
returntrue;
}
if (_textBox.Text.Length < MinLength || _textBox.Text.Length > MaxLength)
{
returnfalse;
}
returntrue;
}
Override the AddAttributesToRender(HtmlTextWriter writer) method to support the client side validation:
/// <summary>
/// Add the maximum and minimum attribute for the control
/// </summary>
/// <param name="writer"></param>
protectedoverridevoid AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (base.RenderUplevel)
{
writer.AddAttribute("MinLength", this.MinLength.ToString());
writer.AddAttribute("MaxLength", this.MaxLength.ToString());
}
}
Register in the OnLoad event our client site script file:
/// <summary>
/// Add the controls script file to the page
/// </summary>
/// <param name="e"></param>
protectedoverridevoid OnLoad(EventArgs e)
{
if (Enabled && base.EnableClientScript)
{
Page.ClientScript.RegisterClientScriptResource(typeof(LengthValidator), "LengthValidator.LengthValidator.js");
}
base.OnLoad(e);
}
and ofcourse the client side validation method:
function ValidateLength(source, args) {
var control = document.getElementById(source.controltovalidate);
if( control )
{
args.IsValid = ( control.value.length >= source.getAttribute('MinLength') && control.value.length <= source.getAttribute('MaxLength') );
}
}
The full class library project source can be downloaded below. Just compile it, add it to the toolbox and use it as any other Validator