jQuery验证插件 - 如何创建一个简单的自定义规则?

2022-08-29 23:37:43

如何使用不使用正则表达式的jQuery Validate插件(使用addMethod)创建一个简单的自定义规则?

例如,什么函数将创建仅在选中一组复选框中的至少一个时才进行验证的规则?


答案 1

您可以通过执行如下操作来创建一个简单的规则:

jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");

然后像这样应用:

$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});

只需更改“添加方法”的内容即可验证您的复选框。


答案 2
$(document).ready(function(){
    var response;
    $.validator.addMethod(
        "uniqueUserName", 
        function(value, element) {
            $.ajax({
                type: "POST",
                url: "http://"+location.host+"/checkUser.php",
                data: "checkUsername="+value,
                dataType:"html",
                success: function(msg)
                {
                    //If username exists, set response to true
                    response = ( msg == 'true' ) ? true : false;
                }
             });
            return response;
        },
        "Username is Already Taken"
    );

    $("#regFormPart1").validate({
        username: {
            required: true,
            minlength: 8,
            uniqueUserName: true
        },
        messages: {
            username: {
                required: "Username is required",
                minlength: "Username must be at least 8 characters",
                uniqueUserName: "This Username is taken already"
            }
        }
    });
});