jQuery正则表达式,远程验证

时间:2010-09-23 14:52:04

标签: jquery regex

我有这个:

    <script type="text/javascript">

jQuery().ready(function() {

    // validate signup form on keyup and submit
    jQuery("#regform").validate({
        rules: {
            NickName: {
                required: true,
                minlength: 2,
                remote : "user_availability.php",
            },
        },
        messages: {
             NickName:{
                      required: "<br>Please enter your username",
                      minlength : "<br>Your username must be at least 2 characters long",
                      remote: "<br>This username is not available, please try another"
                     }
        }
    });
});
</script>

当我尝试添加此处找到的任何addMethod正则表达式示例时,它将无法正常工作

这就是我的尝试:

<script type="text/javascript">

jQuery().ready(function() {

jQuery.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var check = false;
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
);



    // validate signup form on keyup and submit
    jQuery("#regform").validate({
        rules: {
            NickName: {
                required: true,
                minlength: 2,
                remote : "user_availability.php",
                regex: "^[a-zA-Z'.\s]{1,40}$",
            },
        },
        messages: {
             NickName:{
                     required: "<br>Please enter your username",
                     minlength : "<br>Your username must be at least 2 characters long",
                     remote: "<br>This username is not available, please try another"
                     regex: "Invalid Character",
                    }    
        }
    });
});
</script>

请帮助

1 个答案:

答案 0 :(得分:0)

您错过了,

remote: "<br>This username is not available, please try another" <<<<<

并且您不需要对象的最后一个元素上的',':

NickName: {
                required: true,
                minlength: 2,
                remote : "user_availability.php",
                regex: "^[a-zA-Z'.\s]{1,40}$",
            },   <<<<<<<

就个人而言,我会让整个想法更整洁

var ValidationObject = {
    rules: {
        NickName: {
            required: true,
            minlength: 2,
            remote : "user_availability.php",
            regex: "^[a-zA-Z'.\s]{1,40}$",
        }
    },
    messages: {
        NickName:{
            required: "<br>Please enter your username",
            minlength : "<br>Your username must be at least 2 characters long",
            remote: "<br>This username is not available, please try another",
            regex: "Invalid Character",
        }
    }
}

然后像这样使用:

jQuery("#regform").validate(ValidationObject);