正则表达式不起作用

时间:2013-02-06 12:55:02

标签: jquery regex 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>

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"
     },

3 个答案:

答案 0 :(得分:6)

请改为尝试:

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

正则表达式部分:

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

如果必须在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.
});

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

答案 1 :(得分:1)

这个应该做的:

/^(?=\w{6,12}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d).*/

有关其工作原理的详细信息,请点击此处

http://www.asiteaboutnothing.net/regex/regex-lookarounds.html

本文中的最大长度为10,但将其转换为12则很简单。

答案 2 :(得分:1)

jQuery.validator.addMethod("passcheck", function(value, element) {
     var upperCase= new RegExp('[A-Z]');
     var lowerCase= new RegExp('[a-z]');
     var numbers= new RegExp('[0-9]');
     return this.optional(element) || (value.match(upperCase) && value.match(lowerCase) && value.match(numbers) && value.length >=6 && value.length <=12);
}, "* Your password must be between 6 and 12 characters. It must contain a mixture of uppercase, lowercase, and digits");
rules:{
    password1: {
       required: true,
       passcheck: true
    }
},