显示服务器端验证的验证错误

时间:2012-01-18 22:26:53

标签: c# jquery asp.net-mvc

我有一个ajax表单,里面有一个编辑器 - 一个模型,其中包含带有自定义验证属性的电子邮件字段,用于检查服务器中是否已存在电子邮件,因此它是这样的:

$("#submitPop").live("click", (function (e) {
       var form = $("#popForm");
        form.validate();
        if (form.valid()) {
            $.ajax({
                type: "POST",
                url: "/Account/RegisterEmail/",
                data: form.serialize(),
                dataType: "json",
                success: function (result) {
                    if (result.Status) {
                        location.reload(true);
                    } else {
                        alert("Something Went Wrong!"); //what should i write here to show the error message in its generated field-validation-error span
                    }
                }
            });
        }
        return false;

    }));

在ajax表格中:

       @Html.EditorFor(x => x.Email)
       @Html.ValidationMessageFor(x => x.Email)</li>

因为注释说明当ajax结果返回false时,为了在生成的字段验证错误范围中显示错误消息,我该怎么做?

我正在考虑一种本地方式来通知jquery错误并通知jquery更改所有需要的更改,例如放置红色X并使错误范围字体变为红色等等 类似的东西:

$.Validator.ShowErrorMessageFor("Email","Email is Already Taken")

3 个答案:

答案 0 :(得分:2)

  

如果您使用的是ASP.net,MVC3会建议使用远程验证   属性

     

错误消息将在“字段验证错误消息跨度”中呈现。

ASP.NET MVC 3 provides a mechanism that can make a remote server call in order to validate a form field without posting the entire form to the server. This is useful when you have a field that cannot be validated on the client and is therefore likely to fail validation when the form is submitted. For example, many Web sites require you to register using a unique user ID. For popular sites, it can take several attempts to find a user ID that is not already taken, and the user's input is not considered valid until all fields are valid, including the user ID. Being able to validate remotely saves the user from having to submit the form several times before finding an available ID.

请参阅此SO question remote-validation-in-asp-net-mvc-3-或参阅MSDN Article

答案 1 :(得分:0)

我假设范围的Id是field-validation-error,那么它应该是,

$('#field-validation-error').text('Email already exist, Please enter a different email ID');

答案 2 :(得分:0)

首先,将id设置为span:

<span class="field-validation-error" id="validEmail"></span>

然后你可以使用:

$('#validEmail').text('Email already exist...');