我尝试使用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 函数中添加了几行代码,但我没有得到这个想法。你能帮帮我吗?这对我来说会很棒。提前致谢
答案 0 :(得分:4)
您可以使用indexOf()
检查元素是否存在于数组中并返回true
或false
。如果找到元素,indexOf()
将返回数组中元素的索引。请参阅工作代码段:
$(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;
您可以详细了解indexOf()
如何运作 here 。