简体   繁体   English

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

[英]How can I validate a full name using addMethod in jQuery Validator?

I'm currently using jQuery Validate to validate my form data, and I'm using regex for several fields to check validity using patterns.我目前正在使用 jQuery Validate 来验证我的表单数据,并且我正在对几个字段使用正则表达式来检查使用模式的有效性。 However, even after applying my new validation method via addMethod, the form still allows people to submit the form using only a first name in the full name field.但是,即使在通过 addMethod 应用我的新验证方法之后,表单仍然允许人们仅使用全名字段中的名字来提交表单。

For my full name field, I've already verified my regex works by testing it on the field without using novalidate on my form.对于我的全名字段,我已经通过在字段上测试它来验证我的正则表达式是否有效,而没有在我的表单上使用 novalidate。

Regex: ^([a-zA-Z]{2,}\\s[a-zA-z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)正则表达式: ^([a-zA-Z]{2,}\\s[a-zA-z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)

addMethod attempt 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>

If a single name (eg John) is entered instead of a full name, my regex should mark it invalid and request the person's full name.如果输入的是单个姓名(例如 John)而不是全名,我的正则表达式应该将其标记为无效并请求该人的全名。

You need to do two things:你需要做两件事:

  • First, return true if you validation passes, false otherwise.首先,如果验证通过则返回true ,否则返回false

  • Second, actually invoke the newly-added method in .validate() .其次,实际调用.validate()新增的方法。

This can be seen in the following:这可以在以下内容中看到:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM