Angular2材质:角度材质输入的自定义验证

时间:2017-10-11 20:20:25

标签: typescript error-handling angular2-forms angular-material2

在我的Angular 2和材料应用程序中,我想检查用户名是否已经使用。如果已经采取,那么它应该显示错误。

我正在遵循以下指南 https://material.angular.io/components/input/overview#error-messages

打字稿文件

import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

const existingUserNames = ['rohit', 'mohit', 'ronit'];

@Component({
   selector: 'input-errors-example',
   templateUrl: 'input-errors-example.html',
   styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {

    emailFormControl = new FormControl('', [
         Validators.required
    ]

    // I want to call below isUserNameTaken function but dont know 
    // how to use it with Validators so that error message will be visible.

    isUserNameTaken() : boolean {
       this.attributeClasses = attributeClasseses;
       this.attributeClasses.find( object => {
           if(object.attributeClass === this.attributeClass) {
               console.log("found " + JSON.stringify(object));
               return true;
           }
       });
       return false;
   }
}

HTML

 <form class="example-form">
   <md-form-field class="example-full-width">
     <input mdInput placeholder="Email [formControl]="emailFormControl">
    <md-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </md-error>

  <!-- I want to make something like that - custom validation -->

     <md-error *ngIf="emailFormControl.hasError('username-already-taken')">
        Username is already taken. Please try another.
    </md-error>
  <!-- custom validation end -->        

     </md-form-field>

1 个答案:

答案 0 :(得分:3)

您只需要更改函数以接收组件作为参数,如果一切正常则返回null,如果不是则返回错误对象。然后,将它放在组件验证器的数组上。

// Control declaration
emailFormControl = new FormControl('', [
   Validators.required, 
   isUserNameTaken
]

// Correct validator funcion
isUserNameTaken(component: Component): ValidationErrors {
    this.attributeClasses = attributeClasseses;
    this.attributeClasses.find( object => {
        if(object.attributeClass === this.attributeClass) {
            console.log("found " + JSON.stringify(object));
            // found the username
            return {
                username-already-taken: {
                    username: component.value
                }
            };
        }
    });
    // Everything is ok
    return null;
}

Will Howell对评论提出的链接中更深入地解释了这一点。它还解释了如何对非反应形式做同样的事情。

Tutorial