Conditional Validation using JQuery Validation Plugin

后端 未结 3 2020
孤街浪徒
孤街浪徒 2020-12-29 08:57

I have a simple html form that I\'ve added validation to using the JQuery Validation plugin. I have it working for single fields that require a value. I now need to extend t

相关标签:
3条回答
  • 2020-12-29 09:37

    You can do something like this:

    $("#editRecord").validate({
        rules: {
            'Details1': {
                required: function() {
                    return $('input[name=Question1]').val() == 'yes';
                }
            }
            'Details2': {
                required: function() {
                    return $('input[name=Question2]').val() == 'yes';
                }
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-29 09:38

    On your <textarea> elements, add a dependency expression for required, for example for question 1, do this:

    validate="required:'input[name=Question1][value=Yes]:checked'"
    

    This says if $('input[name=Question1][value=Yes]:checked').length > 0 then the field is required, so if Yes is checked, it's required :)

    You can see a working demo here

    0 讨论(0)
  • 2020-12-29 09:57

    In response to Nick Craver's suggested response above, I found the correct syntax to be:

    class="validate[required][name=Question1][value=Yes]:checked"

    instead of what he posted.

    Thanks for putting me on the right track, though!

    0 讨论(0)
提交回复
热议问题