Add/Remove form validations with data attributes on the fly using jQuery Validation Plugin 1.11.1

3.7k views Asked by At

I am using jQuery Validation Plugin to work with form validation that too using data attributes like

<input type="text" class="firstName" name="firstName" data-rule-required="true" /> 

JSFiddle - http://jsfiddle.net/ylokesh/SLXhR/135/

Normal Scenario: It works well if i didn't click on submit button and change the dropdown values and click the submit button.

Problematic Scenario: As soon as i click on submit button then try to change the dropdown value. It won't disable/enable required validation.

Steps to reproduce the actual issue

  • Hit form submit button to fire the required field validation
  • Input field will show up the error message
  • Now change the country dropdown value to make input field non required
  • Error message should disappear this time but it is not the case

JavaScript

$('#validate-me-plz').validate();

$("#country").change(function(){
    if($(this).val() === "country1") {
        if($('.firstName').attr('data-rule-required') !== 'true') {
            $('.firstName').attr('data-rule-required','true');    
        }
    } else if($(this).val() === "country2") {
        if($('.firstName').attr('data-rule-required') !== 'false') {
            $('.firstName').attr('data-rule-required','false');    
        }
    }
});

Please guide me to get the resolution for this issue. Thanks in advance.

1

There are 1 answers

5
Guruprasad J Rao On BEST ANSWER

Use data instead of attr and instead of setting string true or false set a bool value

DEMO

$("#country").on('change',function(){
    if($(this).val() === "country1") {
        if(!$('.firstName').data('rule-required')) { //check bool value
            $('.firstName').data('rule-required',true);    //set bool value
        }
    } else if($(this).val() === "country2") {
        if($('.firstName').data('rule-required')) {
            $('.firstName').data('rule-required',false);    
        }
    }
});