Angular 2 (beta) Server Side Validation Messages

I am looking for an elegant way to display validation messages from the server-side API without having to create custom validators or hard-code all possible messages in the user interface.

I need to add error messages to certain fields as well as to the whole form.

This should work in Angular 2.0.0-beta.3

+5
source share
2 answers

I present to you the final displayErrors function (handles server-side validations according to the JSONAPI standard ):

You will need Underscore.js

displayErrors(error: ErrorResponse) {
  let controls = this.supportRequestForm.controls;
  let grouped = _.groupBy(error['errors'], function(e) {
    return e['source']['pointer'];
  });
  _.each(grouped, function(value, key, object) {
    let attribute = key.split('/').pop();
    let details = _.map(value, function(item) { return item['detail']; });

    controls[attribute].setErrors({ remote: details.join(', ') });
  });
}
+3
source

:

  • ( )
  • ,

, :

@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})`;
               }
             );
  }
}

, JSON :

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

, , :

@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.http.post('http://...', data)
             .map(res => res.json())
             .subscribe(
               (data) => {
                 // Success callback
               },
               (errorData) => {
                 // Error callback
                 var error = errorData.json();
                 var messages = error.messages;
                 messages.forEach((message) => {
                   this.companyForm.controls[message.property].setErrors({
                     remote: message.message });
                 });
               }
             );
  }
}

, JSON :

{
  messages: [
    {
      "property": "name",
      "message": "The value can't be empty"
  ]
}

:

+18

Source: https://habr.com/ru/post/1016826/


All Articles