正则表达式不起作用

jal*_*jal 0 regex jquery jquery-validate

我试图验证一个文本字段类型的密码,但是当我试图写密码时,验证不起作用.用于验证:minlength 6,maxlength 12,uppercase,lowercase和digits

HTML

<tr>
    <td>Contraseña *</td>
    <td>
        <input type="password" name="password1" id="password1">
    </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

JAVASCRIPT

 $.validator.addMethod("password1", function (value, element) {
     return this.optional(element) || /^(?=.*\d)(?=.*[a-zA-Z]).{6,12}$/i.test(value);
 });

 $("#frmDatos").validate({
     errorContainer: contenedor,
     errorLabelContainer: $("ol", contenedor),
     wrapper: 'li',
     meta: "validate",
     rules: {
         password1: {
             required: true
         }
     },
     messages: {
         password1: "La contraseña no es válida"
     },
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 6

试试这个:

/^[a-zA-Z0-9]{6,12}$/.test(value)
Run Code Online (Sandbox Code Playgroud)

正则表达式部分:

# /           - Start regex
# ^           - Match the beginning of the string,
# [a-zA-Z0-9] - Followed by any character that's within the a-z, A-Z, or 0-9 range,
# {6,12}      - And there's between 6 and 12 of these characters,
# $           - Followed by the end of the string (So not followed by any other characters)
# /           - End regex.
Run Code Online (Sandbox Code Playgroud)

当必须在PW中找到所有3个元素时,最简单且可能最易读的事情是:

$.validator.addMethod("password1", function (value, element) {
    return /^.{6,12}$/.test(value) && // The string is between 6-12 characters long,
                 /\d/.test(value) && // And contains a digit,
             /[A-Z]/.test(value) && // And contains a upper-case letter,
            /[a-z]/.test(value)    // And contains a lower-case letter.
});
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,如果字符串与长度要求不匹配,则不会评估其余的正则表达式.它是一个"短路"操作符,这意味着,如果操作符剩下的值是false,则不能进行完整操作true,因此不会评估右侧.