开发者

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开发者_如何学JAVA 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"?


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);
}


Don't enable them until just before the submit, I think you should be able to enable them on the submit instead using a javascript function called by using RegisterOnSubmitStatement, it will fire before the validation afaik.

http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registeronsubmitstatement.aspx

This will save you having to post back.


See by default your Required Field Validator is Enabled (if not then make it). So use only those condition which requires it to disable and you are done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜