1

在我的Angular 2和材质应用程序中,我想检查用户名是否已经被使用。如果它已经被采用,那么它应该显示错误。Angular2材质:对角度材质输入的自定义验证

我在下面的指南。
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> 

+0

也许看看这篇文章https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html? –

+1

你是否设法让它工作?如果是的话,你可以分享你的解决方案。 – jowey

回答

1

你只需要改变你的函数接收组件作为参数和返回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