conditional form validation using jquery.validate.js plugin

前端 未结 2 541
时光说笑
时光说笑 2021-01-05 23:57

Can anyone tell me how to write a rule that validates if neither one radio button option nor the (optinal) textfield is chosen/filled by a user? The rule should only give a

相关标签:
2条回答
  • 2021-01-06 00:17

    The required parameter in jQuery Validate can take a function.

    $('#myForm').validate({
        rules: {
            email2: {
                required: function(element) {
                    if ($('[name="myradiogroup"]:checked').length) {
                        return false;
                    } else {
                        return true;
                    }
                }
            },
            myradiogroup: {
                required: function(element) {
                    if ($('#email2').val()) {
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        }
    });
    

    Here's a condensed version from Sparky

    $('#myForm').validate({
        rules: {
            email2: {
                required: function(element) {
                    return !$('[name="myradiogroup"]:checked').length;
                }
            },
            myradiogroup: {
                required: function(element) {
                    return !$('#email2').val();
                }
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-06 00:24

    maybe can this:

    $('#myForm').submit(function() {
        if($('input:radio').val() == '' || $('#email2').val() == '') {
            preventDefault();
            // show error
        }
    }
    
    0 讨论(0)
提交回复
热议问题