Client Side Validation Using WebApi

I am trying to do client-side validation on my objects that are returned via WebApi. I submit the object via webapi to the Entity edit screen. I use knockout to bind an object to fields.

I already have an action filter that handles all server-side validation. How can I enable client-side validation without duplicating annotations of domain model data?

+7
source share
2 answers

Using WebApi, you will need a small β€œgluing” code to connect errors that return from model validation failures to client-side validators.

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 } 

The model annotates 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) 
+1
source

When I create my HTTP API, I put the model objects (DTO, request models, etc.) in a separate assembly that I can distribute to .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 the same model in an ASP.NET MVC client application, for example, to generate HTML inputs with data- validation data- , because ASP.NET MVC has a way to generate data based on data annotation validation attributes.

0
source

All Articles