使用WebApi进行客户端验证

问题描述:

我正在尝试对通过WebApi返回的对象执行客户端验证.我通过webapi将实体发送到我的实体编辑屏幕.我使用敲除将对象绑定到字段.

I am attempting to perform client side validation on my objects that come back through WebApi. I send the entity through webapi to my Entity edit screen. I use knockout to bind the object to the fields.

我已经有一个动作过滤器来处理所有服务器端验证. 如何在不重复域模型数据注释的情况下合并客户端验证?

I already have an action filter handling all the server side validation. How could I incorporate the client side validation without having to duplicate my domain model data annotations?

使用WebApi,您需要一些胶水"代码来将模型验证失败带来的错误连接到客户端验证器.

With WebApi, you need a little "glue" code to connect the errors coming back from model validation failures to the client side validator.

function extractErrors(jqXhr, validator) {
    var data = JSON.parse(jqXhr.responseText), // parse the response into a JavaScript object
        errors = {};

    $.each(data.ModelState, function (key, value) {
        var pieces = key.split('.');
        key = pieces[pieces.length - 1];
        errors[key] = value
    });

    validator.showErrors(errors); // show the errors using the validator object
}

在模型上,像往常一样注释:

On the model, annotate as usual:

[Required]
[Display(Name = "Group Name")]
public string Name { get; set; }

在视图中,添加ValidationMessageFor标签:

In the view, add the ValidationMessageFor tags:

@Html.EditorFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)