Client Side Validation with WebApi

2019-04-25 11:20发布

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?

2条回答
爷的心禁止访问
2楼-- · 2019-04-25 11:31

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; }

In the view, add the ValidationMessageFor tags:

@Html.EditorFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
查看更多
放我归山
3楼-- · 2019-04-25 11:43

When I create my HTTP API, I put the model objects (DTOs, request models, etc) into a separate assembly which I can distribute for .NET clients.

Consider the following class:

public abstract class UserUpdateRequestModel {

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    [StringLength(320)]
    public string Email { get; set; }
}

This is what I use in my API:

public UserDto PutUser(Guid key, UserUpdateRequestModel requestModel) {

    // Do something here
}

You can use this same model in your ASP.NET MVC client application for example to generate the HTML inputs with validation data- attributes as ASP.NET MVC has a way of generating those based on data annotation validation attributes.

查看更多
登录 后发表回答