1

我有一个带有 SELECT 字段 (college_id) 的表单,我正在尝试对其进行验证。我正在使用 JQuery Validate Plugin 并尝试使用它的“远程”选项。

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!"}

如果出现错误或

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

在没有错误的情况下。(从 Fire Bug 中提取)

问题是,无论响应如何,我都会在 SELECT 字段旁边看到“修复此字段”。只有在出现错误的情况下,我才需要显示我的自定义消息(data.errorMessage)。

4

1 回答 1

1

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

因此,如果一切正常,只需返回 true:

echo json_encode(true);

在你的 php/whatever ajax 调用中。

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

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

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

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

我希望这对其他人有帮助:)

于 2013-07-15T13:29:58.577 回答