简体   繁体   中英

jQuery Validation - password MUST contain uppercase and number

So in my registration form I have this field:

 <div class="form-group">
    <label for="RegisterModel_Password">Password</label>
    <input type="password" id="RegisterModel_Password" 
           name="RegisterModel.Password" class="form-control" 
           required="required" minlength="8"/>
</div>

As you see, I'm using jQuery validation attributes to ensure that the password includes at least 8 characters. So, I want to check if password contains uppercase and number, if not, field is not valid. I downloaded additional method for jQuery Validation plugin named " pattern " and added her in head tag.

I tried to do this as follows but it didn't worked.

$("#formRegister").validate({
    rules: {
        RegisterModel_Password: {
            pattern: /^[a-zA-Z][0-9]/
        }
    }
});

I assume that the pattern is wrong, but I'm not sure whether the use is correct. Thank you for your help.

Chains of regular expressions are too hard for me ( I have never tried to learn them lol ). So here is my solution:

jQuery.validator.addMethod("passwordCheck",
        function(value, element, param) {
            if (this.optional(element)) {
                return true;
            } else if (!/[A-Z]/.test(value)) {
                return false;
            } else if (!/[a-z]/.test(value)) {
                return false;
            } else if (!/[0-9]/.test(value)) {
                return false;
            }

            return true;
        },
        "error msg here");

And simply I use it like a attribute:

<input type="password" id="RegisterModel_Password" 
name="RegisterModel.Password" 
class="form-control" 
required="required" minlength="8" 
passwordCheck="passwordCheck"/>

Thanks for your answers.

You can add your custom validation using $.validator.addMethod() like:

$.validator.addMethod("validation_name", function(value) {
    // at least 1 number and at least 1 character
    [^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
});

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