如何在jQuery验证上添加运算符三元组?

时间:2017-11-03 03:31:50

标签: javascript jquery jquery-validate

我的HTML代码如下:

<form class="validatedForm" id="commentForm" method="get" action="">
    <fieldset>
        <input name="password" id="password" />
        <input name="password_confirmation" />
    </fieldset>
</form>
<button>Validate</button>

我使用jQuery验证的JavaScript代码验证如下:

jQuery('.validatedForm').validate({
    rules: {
        "password": {
            minlength: 6
        },
        "password_confirmation": {
            minlength: 6,
            equalTo : "#password"
        }
    },
      messages: {
            "password": 'Please enter a password, minimal 6 characters',
            "password_confirmation": 'Please confirm your password'
    },
});

演示和完整代码如下:http://jsfiddle.net/oscar11/fEZFB/609/

我想在jQuery验证中添加条件

如果填写了密码,请在password_confirmation

上填写required: true

如果密码未填写,请在password_confirmation

上填写required: false

似乎我需要在规则password_confirmation上添加运算符三元组。但我仍然感到困惑

我该怎么办?

1 个答案:

答案 0 :(得分:0)

我尝试为您的问题做出答案,请查看

&#13;
&#13;
$(document).ready(function() {
  $('.validatedForm').validate({
    rules: {
      "password": {
        minlength: 6,
      },
      "password_confirmation": {
        minlength: 6,
        required: function(element) {
          return $("input[name=password]").val() != "";
      	},
        equalTo : "#password"
      }
    },
    messages: {
      "password": 'Please enter a password, minimal 6 characters',
      "password_confirmation": 'Please confirm your password'
    },
  });

  $('button').click(function () {
    console.log($('.validatedForm').valid());
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/additional-methods.js"></script>

<form class="validatedForm" id="commentForm" method="get" action="">
    <fieldset>
        <input name="password" id="password" />
        <input name="password_confirmation" />
    </fieldset>
</form>
<button>Validate</button>
&#13;
&#13;
&#13;