Monday, October 20, 2008

Prevent CompareValidator passing validation when input control is empty(

I guess you all already know about the comparevalidator when the value of input control(ControlToValidate) is empty/null, it causes the validation success.

Some of you may use requirefieldvalidator to make the field required on input control, but sometime all we want to do is to compate value between two textboxs though they are empty. If both are empty or equal, it pass the validation else validatioin error.

To deal with this problem, my solution is to implement the CustomValidator control.


1. Create a Class Library project in visual studio

2. In solution explorer, Add new item as Custom Control and name the control properly.

3. Override EvaluateIsValid function by adding the following code:

protected override bool EvaluateIsValid()
string strCompare;
string strValue;
strCompare = GetControlValidationValue(this.ControlToCompare).Trim();
strValue = GetControlValidationValue(this.ControlToValidate).Trim();
if (strCompare == strValue)
return true;
return false;

4. Build the project. You will get a ddl file in Bin folder. Finally, you can have fun with your application. Good luck!

No comments: