Thursday 11 June 2009

CompareValidator doesn't fire

I have an application where I am using a CompareValidator on a field that is acting as a CAPTCHA, therefore I am comparing the value that is entered.

When testing the page, I was clicking the submit button on the form, before entering any text, but when I did this, it was submitting the form! Why, when the value couldn't possibly be the same?

The reason for it is the depths of the AJAX js files:

function CompareValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var compareTo = "";
if ((typeof(val.controltocompare) != "string") ||
(typeof(document.getElementById(val.controltocompare)) == "undefined") ||
(null == document.getElementById(val.controltocompare))) {
if (typeof(val.valuetocompare) == "string") {
compareTo = val.valuetocompare;
}
}
else {
compareTo = ValidatorGetValue(val.controltocompare);
}
var operator = "Equal";
if (typeof(val.operator) == "string") {
operator = val.operator;
}
return ValidatorCompare(value, compareTo, operator, val);
}

The following line is the culprit:

if (ValidatorTrim(value).length == 0)
return true;

If the length of the information input into the box being validated is 0, i.e. nothing entered, then this validates as true. This means that if you compare something to nothing, that is valid.... stupid, but valid.

The solution to this is to add a RequiredFieldValidator as well, which then forces the length to be greater than 0, an thus makes it all work

No comments:

Post a Comment