gene b.
gene b.

Reputation: 12006

jQuery Validate on a Complex Rule: Turn off automatically when not applicable but not on startup

In the script below I have a complex jQuery-Validate rule which fires if "Comments" is blank specifically on "Type 2" but not any other case.

Most of the time, jQuery Validate hides messages automatically as errors get corrected before resubmitting the form. In this complex rule, once the error is received, if you go back to "Type 1" the error doesn't disappear.

I tried forcing .valid() on "Comments" on the radio's change() event. But this has the disadvantage that the first time "Type 2" is selected, you automatically see the error before anything's typed in.

My goal: (1) Do not present the error initially as the user selects Types. (2) If the error is received after Submit, switching to Type1 should auto-hide it.

The auto-hide corrections should be both typing something in (this works correctly), or switching the radio button.

jQuery.validator.addMethod("chkType2Comments",checkType2Comments);

$("#myform").validate({
    rules: {
			  "comments": {
        		chkType2Comments: true
        }
    },
    messages: {
        "comments" : {
            chkType2Comments: "Comments required"
        }
    }
});

function checkType2Comments() {
	var type = $('input[name="type"]:checked').val();
	if (type == '2') {
		if ($('input[name=comments]').val().trim() == '') {
			return false;
		}	
	}
	return true;
}

$('#submitForm').click(function() {
   $('#myform').valid();
})

// Radiobutton switching -- if I remove this, the error doesn't go away on switching back.
// But if I leave this code, the error comes up immediately.
// Goal: Error not initially shown, but if Type is switched afterwards, auto-turned off.
/*
$('input[name=type]').change(function() {
    $('input[name=comments]').valid();
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

<form id="myform">

   <input type="radio" name="type" value="1" /> Type 1 <br/>
   <input type="radio" name="type" value="2" /> Type 2 <br/>
   
   <input type="text" name="comments" />

   <input type="button" id="submitForm" value="submit"/>

</form>

Upvotes: 0

Views: 104

Answers (1)

Sparky
Sparky

Reputation: 98738

"My goal: (1) Do not present the error initially as the user selects Types. (2) If the error is received after Submit, switching to Type1 should auto-hide it."

So put your change handler inside of your click handler so that your radio buttons are ignored until the first click of the "submit".

$('#submitForm').on('click', function() {

    $('#myform').valid();

    $('[name="type"]').on('change', function() {
        $('[name="comments"]').valid();
    });

});

DEMO: jsfiddle.net/5hdoc2wv/2/

Upvotes: 1

Related Questions