SP5414 February 2016

Angular 2 (Beta) Server side validation messages

I am looking for an elegant way to display validation messages from a server side API without having to create custom validators or hard coding all possible messages in the UI.

I need to add error messages to specific fields as well as to the entire form.

This must work in Angular 2.0.0-beta.3

Answers


Thierry Templier February 2016

There are two kinds of server validations:

  • The global ones (for the whole form or corresponding to an error during the form submission)
  • The ones related to fields

For the one, simply extract the message from the response payload and put it into a property of your component to display it into the associated template:

@Component({
  (...)
  template: `
    <form (submit)="onSubmit()">
      (...)
      <div *ngIf="errorMessage">{{errorMessage}}</div>
      <button type="submit">Submit</button>
    </form>
  `
})
export class MyComponent {
  (...)

  onSubmit() {
    this.http.post('http://...', data)
             .map(res => res.json())
             .subscribe(
               (data) => {
                 // Success callback
               },
               (errorData) => {
                 // Error callback
                 var error = errorData.json();
                 this.error = `${error.reasonPhrase} (${error.code})`;
               }
             );
  }
}

I assume that the response payload for error is a JSON one and corresponds to the following:

{
  "code": 422,
  "description": "Some description",
  "reasonPhrase": "Unprocessable Entity"
}

For the second one, you can set received error message within controls associated with form inputs, as described below:

@Component({
  (...)
  template: `
    <form [ngFormModel]="myForm" (submit)="onSubmit()">
      (...)
      Name: <input [ngFormControl]="myForm.controls.name"/>
      <span *ngIf="myForm.controls.name.errors?.remote"></span>
      (...)
      <button type="submit">Submit</button>
    </form>
  `
})
export class MyComponent {
  (...)

  constructor(builder:FormBuilder) {
    this.myForm = this.companyForm = builder.group({
      name: ['', Validators.required ]
    });
  }

  onSubmit() {
    this. 

Post Status

Asked in February 2016
Viewed 2,481 times
Voted 9
Answered 1 times

Search




Leave an answer