Jquery validate depend field

可紊 提交于 2019-11-27 20:35:09

You could use depends:

$('#ProspectDtlFrm').validate({ 
    rules: {
        prsptEmail: {
            required: {
                depends: function(element) {
                    return ($('#prsptHomePhone').val() == '' && 
                            $('#prsptBusinessPhone').val() == '' && 
                            $('#prsptMobilePhone').val() == '');
                }
            }
        }    
    }, 
    messages: { 
        prsptEmail: 'Please enter your first name'
    } 
});
vicman4

The depends clause is still supported. This is from 1.11.0pre version:

normalizeRules: function(rules, element) {
  // handle dependency check
  $.each(rules, function(prop, val) {
    // ignore rule when param is explicitly false, eg. required:false
    if (val === false) {
      delete rules[prop];
      return;
    }
    if (val.param || val.depends) {
      var keepRule = true;
      switch (typeof val.depends) {
        case "string":
          keepRule = !!$(val.depends, element.form).length;
          break;
        case "function":
          keepRule = val.depends.call(element, element);
          break;
      }
      if (keepRule) {
        rules[prop] = val.param !== undefined ? val.param : true;
      } else {
        delete rules[prop];
      }
    }
  });

As you can see, yo can choose between "string" and "function". So you can use:

rules: {
  input_name_here: {
    required: {
      depends: function(element) {
        return $("#thickBoxId:checked").length;
        //or whatever you need to check
      }
    }
  }
}

Or

rules:{
  input_name_here:{
    required: '#tickBoxId:checked'
  }
}

If you only need to test for the existence of something checked.

'depends' seems like it's not supported any more, and, their docs are not up to date.

So in the scenario where if a 'yes' tick box is checked, validate another field:

rules:{
    'name value of area you want to validate':{
        required: '#tickBoxId:checked'
    }
}

the way is depends it's works.

    rules: {
        prsptEmail: {
            required: {
                depends: function(element){
                    if ($('#id-user').val() == '') {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        },
    },
    messages: {
        prsptEmail : {
            required : "please signIn!",
        }
    },
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!