Enabling - but not firing - a RequiredValidator using jQuery / javascript
Asked Answered
D

3

5

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"?

Discursion answered 14/6, 2011 at 13:27 Comment(0)
R
13

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);
}
Ricebird answered 16/6, 2011 at 8:29 Comment(0)
C
0

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.

Collimate answered 14/6, 2011 at 13:38 Comment(0)
O
0

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.

Olivier answered 8/2, 2013 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.