如何在jQuery Validator中使用addMethod验证全名



我目前正在使用jQuery Validate来验证我的表单数据,并且我正在对几个字段使用regex来使用模式检查有效性。然而,即使通过addMethod应用了我的新验证方法,表单仍然允许人们在全名字段中只使用名字提交表单。

对于我的全名字段,我已经通过在字段上测试regex来验证它的有效性,而不在我的表单上使用novalidate

Regex:^([a-zA-Z]{2,}s[a-zA-z]{1,}'?-?[a-zA-Z]{2,}s?([a-zA-Z]{1,})?)

addMethod尝试

jQuery.validator.addMethod("fullname", function(value, element) {
return this.optional(element) || /^([a-zA-Z]{2,}s[a-zA-z]{1,}'?-?[a-zA-Z]{2,}s?([a-zA-Z]{1,})?)/.test(value);
}, 'Please enter your full name.');
<input id="full-name" name="Full_Name" type="text" class="form-control" placeholder="John Doe" required>

如果输入的是一个单独的名字(例如John)而不是全名,我的正则表达式应该将其标记为无效,并请求该人的全名。

您需要做两件事:

  • 首先,如果验证通过,则返回true,否则返回false

  • 其次,实际上调用.validate()中新添加的方法。

这可以在以下内容中看到:

jQuery.validator.addMethod("fullname", function(value, element) {
if (/^([a-zA-Z]{2,}s[a-zA-z]{1,}'?-?[a-zA-Z]{2,}s?([a-zA-Z]{1,})?)/.test(value)) {
return true;
} else {
return false;
};
}, 'Please enter your full name.');
$("#sample").validate({
rules: {
Full_Name: { // Corresponds to the `name` attribute
required: true,
fullname: true // Attaches the new method to the element
}
},
submitHandler: function(form, e) {
e.preventDefault();
console.log('The form is valid and would have been submitted successfully');
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<form id="sample">
<input id="full-name" name="Full_Name" type="text" class="form-control" placeholder="John Doe" required>
<button id="submit">Submit</button>
</form>

最新更新