Jquery Validator,检查数组中是否存在输入名称

时间:2017-01-10 10:23:53

标签: jquery jquery-validate

我尝试使用Jquery验证器验证我的表单,如果输入名称在数组中,它应该返回自定义验证器错误消息(已经存在),请看下面的代码,我试过几个,但是我无法达到如何实现这一目标。

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Validator</title>
</head>
<body>
    <div>
        <form id="MyForm" action="." type="post">
            <input type="text" name="name">
            <button type="submit">Save</button>
        </form>
    </div>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var name_list = ["Danny", "Bucky", "James"]
            jQuery.validator.addMethod("alreadyexist", function(value, element) {
                .....
                .....
                .....
            }, "The Name is already Exist");

            $("#MyForm").validate({
                rules: {
                    "name": {
                        required: true,
                        alreadyexist: true,

                    },
                },
            });

        });
    </script>
</body>
</html>

我知道在 addMethod 函数中添加了几行代码,但我没有得到这个想法。你能帮帮我吗?这对我来说会很棒。提前致谢

1 个答案:

答案 0 :(得分:4)

您可以使用indexOf()检查元素是否存在于数组中并返回truefalse。如果找到元素,indexOf()将返回数组中元素的索引。请参阅工作代码段:

&#13;
&#13;
$(document).ready(function() {
   var name_list = ["Danny", "Bucky", "James"]
   $.validator.addMethod("alreadyexist", function(value, element) {
     return name_list.indexOf(value) == -1;
   }, "The Name is already Exist");

   $("#MyForm").validate({
     rules: {
       "name": {
         required: true,
         alreadyexist: true
       }
     }
   });

 });
&#13;
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<div>
  <form id="MyForm" action="." type="post">
    <input type="text" name="name">
    <button type="submit">Save</button>
  </form>
</div>
&#13;
&#13;
&#13;

您可以详细了解indexOf()如何运作 here