Jquery验证插件,使用自定义错误消息进行远程验证

时间:2012-09-29 05:45:01

标签: php jquery jquery-validate

我有一个带有SELECT字段(college_id)的表单,我正在尝试验证。 我正在使用JQuery Validate插件并试图使用它"远程"选项。

HTML:

<form id="registration-form" ... >
.
.
<select name="college_id" id="college_id" class="required" >
//Options generated using PHP code
</select>
.
.
</form>

JAVASCRIPT:

$(document).ready(function(){
    //For triggering the validation onChange
    $('#college_id').change(function(){
        $("#college_id").removeData("previousValue");
        $("#registration-form").validate().element("#college_id");
    });

    $('#registration-form').validate({
        rules:{
            college_id:{
                remote: {
                    type: 'POST',
                    url: urls.base_url+'Representative/checkCollegeAJAX/',
                    dataType:"json",
                    data:{
                        college_id:function(){
                            return $('#college_id').val();
                        }
                    },
                    dataFilter: function(data) {
                        data=JSON.parse(data);
                        console.log(data.isError);
                        if(!data.isError) { //If no error
                            return true;
                        } else {
                            console.log("Error Message: "+data.errorMessage);
                            return "\"" + data.errorMessage + "\"";
                        }

                    }
                }
            }
        }
    });


});

如上所示,当isError == True

时,我试图显示错误消息

我的PHP代码返回一个JSON编码对象,如:

{"isError":true,"errorMessage":"Sorry!"}

如果出现错误 OR

{"isError":false,"errorMessage":""}

如果没有错误。 (从Fire Bug中提取)

问题在于,无论回应是什么,我都会继续&#34;修复此字段&#34;在SELECT字段旁边。 只有在出现错误的情况下,我才需要显示自定义消息(data.errorMessage)。

1 个答案:

答案 0 :(得分:1)

我刚才遇到了这个问题,解决方案是以JSON的形式返回你想要显示为错误的字符串。

所以,如果一切正常,只需返回true:

echo json_encode(true);

在你的php /无论ajax调用。

相反,如果您必须显示错误,请将字符串放在答案中:

echo json_encode("hey, we got something wrong here..");

如果您需要本地化错误消息而您无法通过控制器执行此操作,只需在调用远程方法时将其传递:

data: {
    ajax: true,
    id: function() {
        return $( "#cid" ).val();
    },
    errormsg: "ERROR MSG WITH LOCALE"
},

我希望这能帮助别人:)

相关问题