Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling - but not firing - a RequiredValidator using jQuery / javascript

I have a form with maybe 10 fields. One of those fields is a checkbox, default unchecked, and a number of the fields on the form are only enabled+required if that box is checked. I've successfully found out how to invoke ValidatorEnable(requiredFieldValidator, true) to handle this (I've checked out numerous StackOverflow questions on the subject).

 function toggleStatus() {
          if ($('#ctl00_main_chkContactMe').is(':checked')) {
              $('#elementsToOperateOn :input').removeAttr('disabled');
              $('#elementsToOperateOn label').removeClass('off');
              ValidatorEnable($("[id$=RequiredFieldValidator1]")[0], true);
              ValidatorEnable($("[id$=RequiredFieldValidator2]")[0], true);
          } else {
              $('#elementsToOperateOn :input').attr('disabled', true);
              $('#elementsToOperateOn label').addClass('off');
              ValidatorEnable($("[id$=RequiredFieldValidator1]")[0], false);
              ValidatorEnable($("[id$=RequiredFieldValidator2]")[0], false);
          }
      }

However, I'm having a problem I don't yet see addressed. When my user checks the box and the fields are now enabled and required, my validator immediately fires its "This field is required" message. This is before the user's even had a chance to type anything, so it's not a very good user experience. What can I tell the Validator so that it knows, even though I'm enabling it, "This field hasn't had the focus at all yet, so don't show an error message until somebody has deliberately left it empty"?

like image 758
ShakespeareGeek Avatar asked Jun 14 '11 13:06

ShakespeareGeek


1 Answers

I had the same issue and solved it using this code:

var myValidator = document.getElementById('<%=myValidator.ClientID %>');
ValidatorEnable(myValidator, true);
myValidator.isvalid = true;
ValidatorUpdateDisplay(myValidator);

The third row might look a bit wierd, but the validator will later be validated on any change or on posting off the page.

You could also try this function:

function myValidatorEnabler(validator, enable) {   
    validator.enabled = enable;
    ValidatorUpdateDisplay(validator);
}
like image 116
Mohag519 Avatar answered Nov 02 '22 01:11

Mohag519