I'm a bit confused about the topic form validation / model validation with WebAPI 2 and AngularJS. In AngularJS I'm using the form validation in my view as follows:
<div class="form-group-sm has-feedback" ng-class="myForm.name.$error.required ? 'has-error' : 'has-success'">
<label class="control-label" for="name-id">Name</label>
<input type="text"
class="form-control"
placeholder="Name"
name="name"
id="name-id"
ng-model="selected.name"
ng-required="true"
popover-placement="bottom"
popover-animation="true"
popover="Field must contains at least 4 letters."
popover-trigger="focus"
/>
The popover message should be displayed only when the input field has less than 4 letters. Alternate I've defined by default this error:
<div class="error" ng-show="myForm.name.$dirty && myForm.name.$invalid">
<div class="error" ng-show="myForm.name.$error.required">Field must contains at least 4 letters.</div>
</div>
I'm also using the bootstrap classes has-error
and has-success
for the corresponding message color.
Currently in my WebAPI 2 I'm using model validation as follows:
//Model
public int Id { get; set; }
[Required]
[MaxLength(20, ErrorMessage="Field must contains at least 5 letters.")]
public string name { get; set; }
In my Ctrl I'm using the ModelState method.
//Controller
[HttpPost]
public HttpResponseMessage PostPerson(Person item)
{
if (ModelState.IsValid)
{
item = _rep.Add(item);
var response = Request.CreateResponse<Person>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
Intentionally I have taken a different number in the error message of my WebApi to show the message of the WebApi in the view. My question is, what is good practice? To define the message on client-side or server-side and returns the message on the client-side? How can I send the error messages from my model Person to the view on the client-side? And is it good to define ModelState
in the controller? I've read some articles, that using a filter e.g. ValidateModelAttribute : FilterAttribute
is better than define the ModelState
in the Controller.. but why?