jQuery Validate - Only allow one out of two

前端 未结 4 382
我在风中等你
我在风中等你 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:10

    You could keep a variable with the amount of validated items:

    validatedItems : 0,
    
    mobile : {
        var self = this;
        required: function(element) {  
            if ($("#telephone").val().length > 0) {
                self.validatedItems--;
                return false;
            }
            else {
            self.validatedItems++;
                return true;
            }
        }
    },                                               
    telephone: {
        var self = this;
        required: function(element) {
            if ($("#mobile").val().length > 0) {
                self.validatedItems--;
                 return false;
             }
             else {
                self.validatedItems++;
                return true;
            }
        }
    },
    

    And then you could check if one or more items are validated when you send the form:

    if( validatedItems > 0 ) {
        sendForm();
    }
    

提交回复
热议问题