正则表达式不适用于jquery验证插件

时间:2014-01-06 09:27:34

标签: jquery regex jquery-validate

我正在使用以下代码

$(function() {
    $("#myForm").validate({
        rules: {
            experience: {
                required: true,
                regex: '^[0-9]$'
            }
        },
        messages: {
            experience: {
                required: "Please provide experience",
                regex: "Provide a valid input for experience"
            }
        }
    });
});

但是上面的代码没有将2或22作为有效输入?我做错了什么?需要帮助......

3 个答案:

答案 0 :(得分:12)

请尝试使用此正则表达式:

^[0-9]+$

然后把它放在代码中:

$(function() {
   $.validator.addMethod("regex", function(value, element, regexpr) {          
     return regexpr.test(value);
   }, "Please enter a valid pasword.");    

   $("#myForm").validate({
       rules: {
           experience: {
               required: true,
               regex: /^[0-9]+$/
           }
       }
   });
});

这是一个有效的演示:

http://jsfiddle.net/4PuJL/1/

答案 1 :(得分:3)

验证jquery中没有正则表达式方法: 你必须创建自己的正则表达式方法

您需要使用addmethod

$.validator.addMethod("regx", function(value, element, regexpr) {          
    return regexpr.test(value);
}, "Provide a valid input for experience.");

你的功能在这里:

$(function() {
    $("#myForm").validate({
        rules: {
            experience: {
                required: true,
                regex: /^[0-9]$/
            }
        },
        messages: {
            experience: {
                required: "Please provide experience",

            }
        }
    });
});

<强> add regex in Jquery.validate

答案 2 :(得分:-1)

您可以在.Query的.validate()形式中使用'pattern'关键字而不是'regex'。以下是示例代码:

$('#registerForm').validate({
    rules: {
        "customer[is_seller]": {
            required:true
        },
        "customer[fname]": {
            required:true,
            pattern:/^[A-Za-z]+$/
        },
        "customer[lname]": {
            required:true,
            pattern:/^[A-Za-z\s]+$/
        },
        "customer[email]": {
            required:true,
            email:true
        },
        "customer[password]": {
            required:true
        }
    },
    messages:{
        "customer[is_seller]": {
            required:"Please select Your category"
        },
        "customer[fname]": {
            required:"Please enter first name.",
            pattern:"Special characters not allowed"
        },
        "customer[lname]": {
            required:"Please enter last name."
            pattern:"Special characters not allowed"
        },
        "customer[email]":{
            required:"Email Id is required",
            email:"Please enter a valid email."
        },
        "customer[password]":{
            required:"Password is required"
        }
    }
});