自定义jquery.validate方法始终显示无效

时间:2011-09-21 14:04:02

标签: jquery-validate

我有一个自定义验证方法,用于检查重复的用户名。对于notDuplicateUsername,json正确返回,但验证始终显示为无效。

    $('#register-form').validate({

    //see source of http://jquery.bassistance.de/validate/demo/ for example

    rules: {
        schoolname: {
            required: true
        },
        username: {
            required: true,
            notDuplicateUsername: true
        },
        password: {
            required: true
        },
        email: {
            required: true,
            email: true
        }

    },
    messages: {
        schoolname: 'Please tell us where you want to use Word Strip.',
        username: {
            required: 'Please choose a username.',
            notDuplicateUsername: 'Sorry, that username is already being used.'
        },
        password: 'Please choose a password.',
        email: 'Please can we have your email address.'

    }

});

jQuery.validator.addMethod(
    'notDuplicateUsername', 
    function(value, element, params){

        var toCheck = new Object();
        toCheck['username'] = $('#username').val();

        var data_string = $.toJSON(toCheck);//this is a method of the jquery.json plug in

        $.post('check_duplicate_username.php', {username_data: data_string}, function(result){
            var noDuplicate = true;

            var returned_data = $.evalJSON(result);//this is a method of the jquery.json plug in

            if (returned_data.status == 'duplicate'){
                noDuplicate = false;
            }

            console.log('value of noDuplicate: '+noDuplicate);
            return noDuplicate;
        });

    }
);

有人提出任何线索吗?

1 个答案:

答案 0 :(得分:0)

可能你可能已经对它进行了整理,但以防万一。我遇到了类似的问题,发现我正在比较错误的类型。可能是您的服务器将状态作为布尔值或其他某种数据类型发送,并且它与字符串的比较失败并始终返回false。