jQuery Validate - Only allow one out of two

前端 未结 4 413
我在风中等你
我在风中等你 2021-01-14 07:37

Need a little help. So got a form, where I\'ve got two fields mobile and telephone. Only one is required. My code below does that, but what I would like is I don\'t want peo

4条回答
  •  無奈伤痛
    2021-01-14 08:02

    Use required method with a dependency-espression (jquery selector), this case using a :blank pseudo selector that is part of the validate plugin

    $(form).validate({
       rules
       {
         mobile:{required: '#telephone:blank'}
         telephone:{required: '#mobile:blank'}
       }
    });
    

    from docs - 'Very often your expression will use selector filters such as #foo:checked, #foo:filled, #foo:visible. This plugin provides custom selectors for that purpose.'

    EDIT

    sorry, I didn't fully read the question. The closest method to what you need is the require_from_group method found in the additional-methods.js file of jQuery validate. You need a very minor tweak to test for exactly one validated field from your group.

    eg

    with code

    jQuery.validator.addMethod("require_from_group_exact", function(value, element, options) {
        var validator = this;
        var selector = options[1];
        var validOrNot = $(selector, element.form).filter(function() {
            return validator.elementValue   (this);
        }).length == options[0];
    
        if(!$(element).data('being_validated')) {
            var fields = $(selector, element.form);
            fields.data('being_validated', true);
            fields.valid();
            fields.data('being_validated', false);
        }
        return validOrNot;
    }, jQuery.format("Please fill {0} of these fields."));
    
    $('form').validate({
        rules:{
        partnumber:  {require_from_group_exact: [1,".productinfo"]},
        description: {require_from_group_exact: [1,".productinfo"]}
        }
     });
    

    if you compare this to the original method in addtional-methods.js you will see it is almost the same.

    Hopefully this will help - you need to replace partnumber and description with 'telephone' and 'mobile' and you should be set.

    fiddle here

提交回复
热议问题