简体   繁体   中英

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. 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.

For my full name field, I've already verified my regex works by testing it on the field without using novalidate on my form.

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

addMethod attempt

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.

You need to do two things:

  • First, return true if you validation passes, false otherwise.

  • Second, actually invoke the newly-added method in .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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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