使用正则表达式进行jQuery验证

时间:2018-07-06 07:27:54

标签: jquery html regex

我使用jQuery Validation Plugin来验证电子邮件,用户名,密码...,我试图添加一些正则表达式,但是它不起作用。有人能帮我吗?非常感谢。here is the picture of regex I tried to add

3 个答案:

答案 0 :(得分:0)

您可以使用'pattern:'来匹配正则表达式。下面的代码显示了字符串的正则表达式匹配。希望它能达到您的目的。

$("#your_form").validate({
rules: {
    yourelementName: {
        required:true,
        pattern: /^[a-zA-Z'.\s]{1,40}$/  //this line validates the element with the provided regex expression
    },
},
messages: {
    yourelementName: {
        required:'Please enter the data'
        pattern: 'The Textbox string format is invalid'
    }
}
});

答案 1 :(得分:0)

$('#name').focusout(function () {
    var pattern = /^[a-zA-Z ]{2,30}$/;
    if (pattern.test($("#name").val())) {
        $("#name").css('border-color',
            'green') v1 = 1
    } else {
        $("#name").css('border-color', 'red') v1 = 0
    }
});

执行此操作,使用您要验证文本框的事件。

答案 2 :(得分:0)

如果可以解决您的问题,请尝试以下代码

 $.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    },
    "Your input."
 );

像下面一样进行验证

 $("#field").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })