使用javascript向现有表单添加验证错误?

时间:2012-12-30 14:55:06

标签: jquery ajax asp.net-mvc json validation

我有一个ASP.NET MVC 4,我使用验证属性进行客户端和服务器端验证。

在使用这样的ajax发送表单之前,表单将被正确验证:

function ValidateFormAndAjaxSubmit(formId, callingElement) {

    if (IsNotDblClick(callingElement.id)) {
        var _form = $("#" + formId);

        var validator = _form.validate();
        var anyError = false;

        _form.find("input").each(function () {
            if (!validator.element(this)) { // validate every input element inside this step
                anyError = true;
            }
        });

        if (anyError) {
            window.latestClick = '';
            return false; // exit if any error found    
        }

        $.post(_form.attr("action"), _form.serialize(), function (data) {

            if (data.Success) {

            }
            else {

            }

            alert("Win");
            window.latestClick = '';
            //check the result and do whatever you want
        })
    }
}

表格如下:

@using (Html.BeginForm("JEdit", "Post", FormMethod.Post, new { id = "frmEditPost" }))
{
    @Html.ValidationSummary(true)
    ...
}

将在服务器端进行额外验证,并将其存储在这样的返回类中:

public class JEditResult
    {
        public Boolean Success = false;
        public string TitleErrMessage;
        public string TextErrMessage;
        public string LinkErrMessage;
        public string TagErrMessage;
        public string OtherErrMessage;
    }

现在我需要将这些验证放入表单中,就好像在客户端验证了这些验证一样。我该怎么做?

1 个答案:

答案 0 :(得分:1)

我使用以下扩展方法:

public static JsonResult JsonValidation(this ModelStateDictionary state, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet) {
    var result = new JsonResult {
        Data = new {
            success = false,
            Tag = "ValidationError",
            State = from e in state
                    where e.Value.Errors.Count > 0
                    select new {
                        Name = e.Key,
                        Errors = (e.Value.Errors.Select(x => x.ErrorMessage)
                            .Concat(e.Value.Errors.Where(x => x.Exception != null).Select(x => x.Exception.Message)))
                            .Where(x => !String.IsNullOrEmpty(x)).Select(x => x)
                    }
        }
    };
    result.JsonRequestBehavior = behavior;
    return result;
}

然后在我的代码中使用它,如:

if (ModelState.IsValid == false) {
    Response.StatusCode = 400;
    return ModelState.JsonValidation();
}

我也有一些标准的js代码:

// JSON validation
function validateResponse(form, response) {
    var data = getResponseValidationObject(response);
    if (!data) return true;

    var validator = form.validate();
    var container = form.find("[data-valmsg-summary=true]");
    var list = container.find("ul");
    if (!list) return;

    container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
    list.empty().show();
    $.each(data.State, function (i, item) {
        list.append("<li>" + item.Errors.join("</li><li>") + "</li>");
    });
    return false;
}

// JSON validation
function getResponseValidationObject(response) {
    if (response && response.Tag && response.Tag == "ValidationError")
        return response;
    return null;
}

然后在我的ajax帖子中,我检查返回响应的有效性:

var json = $.parseJSON(response.responseText);
var isValid = validateResponse($("#form"), json);
// Do something here...

validateResponse函数会自动将错误添加到表单验证摘要中(假设有一个)。