1

私のAngular 2および素材アプリケーションでは、ユーザ名がすでに使用されているかどうかをチェックしたいと思います。すでに撮影されている場合は、エラーが表示されます。Angular2 Material:角型材料入力のカスタムバリデーション

下記のガイドに従っています。
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

あなただけのパラメータとしてコンポーネントを受け取り、ヌルを返すために、あなたの関数を変更する必要がありますすべてが正常であればエラーオブジェクト、そうでなければエラーオブジェクトです。次に、それをコンポーネントバリデーターの配列に置きます。

// 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

関連する問題