【问题标题】:Angular 2 (Beta) Server side validation messagesAngular 2(Beta)服务器端验证消息
【发布时间】:2016-02-08 22:43:56
【问题描述】:

我正在寻找一种优雅的方式来显示来自服务器端 API 的验证消息,而无需在 UI 中创建自定义验证器或硬编码所有可能的消息。

我需要将错误消息添加到特定字段以及整个表单。

这必须在 Angular 2.0.0-beta.3 中工作

【问题讨论】:

    标签: validation angular


    【解决方案1】:

    有两种服务器验证:

    • 全局的(用于整个表单或对应于表单提交期间的错误)
    • 与字段相关的那些

    对于第一个,只需从响应负载中提取消息并将其放入组件的属性中以将其显示到关联的模板中:

    @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"
      ]
    }
    

    更多细节你可以看看这个项目:

    【讨论】:

    • 链接好像失效了。
    • @DDiVita 我已经修复了链接。
    【解决方案2】:

    我向您展示了明确的 displayErrors 函数(按照 JSONAPI 标准处理服务器端验证):

    您将需要 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(', ') });
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 2017-08-13
      • 2018-01-17
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      相关资源
      最近更新 更多