简体   繁体   中英

Using JQuery how do I check two fields that I need one filled only

Using jQuery my user only has to enter one field, ssn or phone but how do I check in the jquery validate that one is check?

<script type="text/javascript">
    $(document).ready(function () {
        $("#memberrequest").validate({
            rules: {
                phonenumber: {
                    minlength: 12,
                    maxlength: 12
                },

                ssn: {
                    minlength: 10,
                    maxlength: 10
                }

            }
        });


    });
</script>

Please help me out

I made a fiddle for you based on what you posted, it would still have to be customized but it demonstrates what you are asking.

http://jsfiddle.net/whytheday/QP4wd/1/

$(document).ready(function () {
    $("#memberrequest").validate({
        rules: {
            phonenumber: {
                minlength: 12,
                maxlength: 12,
                required: {
                    depends: function(element){
                        return $("#ssn").val().trim() == ""
                    }
                }
            },

            ssn: {
                minlength: 10,
                maxlength: 10,
                required: {
                    depends: function(element){
                        return $("#phonenumber").val().trim() == ""
                    }
                }
            }

        }
    });
});

You just set it to required and then you can set a dependency and you can check if the other field has a value.

Take a look at the options for "required" http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression . You can specify a dependency expression or a dependency callback. This means you are providing a bit of javascript code (within the class attribute, where the example just says required:true), and you're saying "if my bit of code evaluates as true, then this form element is required".

So in your case, both the phone number and the ssn fields would need dependency expressions that say "if the other one is empty, this one is required".

You could loop over both fields, and see if either has a value:

$( function () {
    var passesValidation = false;

    $('input').each( function() {
        if ( $(this).val() ) { passesValidation = true; } // could add optional check against length for this field
        //  $(this).val().length && $(this).val().length >= $(this).attr('data-minlength') or some such
    });


});

http://jsfiddle.net/nq69r/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM