2017-10-29 7 views
2

私は別の汎用コンポーネントを使用してエラーを表示していると言いたいので、繰り返しは避けるためにhtmlの中に入れていませんテンプレート内で条件付きのハードコードを直接実行できます。Angular2のリアクティブフォームは、検証の失敗条件に基づいてエラーメッセージを表示します

私は、このフィールドを持っており、2つの検証が適用される:

this.username = new FormControl('', [ Validators.minLength(5), Validators.required ]); 

を、私は検証のそれぞれについて、検証エラーメッセージを表示するにはどうすればよいですか?何も提出のフィールドにされていない場合のは、私は両方のエラーを表示したいとしましょう:
「最小の長さが5され、」

そして、あなたはその中に何かを置けばなければならないだけのショーを「フィールドが必要とされる」:
これは一例ですが、それらが同じであれば、私の実際の生活の例では、2つの電子メールのフィールドを比較しているので、メールが正しくされない場合に表示されるはずです

「最小長さは5である」:
「メールが正しくありません "
メールが正しく、電子メールが同じでないのであれば必要がある唯一のショー

「メールが最初のメールフィールドと同じではありません」:

「メールが最初のメールフィールドと同じではありません」

私は合格しなかった場合の検証を行っていますが、1つの検証が成功した場合には別に表示する方法がわからず、失敗した理由を正しく追加して両方の理由を入れないといけません。

フル例:

コンポーネントエラー表示用:

import { Component, OnInit, Input } from '@angular/core'; 

@Component({ 
    selector: 'app-field-error-display', 
    templateUrl: './field.error.display.component.html', 
    styleUrls: ['./field.error.display.component.css'] 
}) 
export class FieldErrorDisplayComponent 
{ 
    @Input() errorMsg: string; 
    @Input() displayError: boolean; 
} 

コンポーネントHTML:Register.htmlでerorrディスプレイの

<div *ngIf="displayError" > 
    <small>{{errorMsg}}</small> 
</div> 

使用:

<form [formGroup]="_form" (ngSubmit)="register()"> 
<h4>Create a new account</h4> 
<div class="form-group"> 
    <label for="email">Email Address</label> 
    <input class="form-control" name="email" formControlName="email" /> 
    <app-field-error-display [displayError]="formValidationService.IsFieldValid(_form,'email')" errorMsg="Please insert correct email"></app-field-error-display> 
</div> 
<div class="form-group"> 
    <label for="emailConfirm">Email Address Confirm</label> 
    <input class="form-control" name="emailConfirm" formControlName="emailConfirm" /> 
    <app-field-error-display [displayError]="formValidationService.IsFieldValid(_form,'emailConfirm')" errorMsg="Please insert correct email"></app-field-error-display> 
</div> 
<div class="form-group"> 
    <label for="password">Password</label> 
    <input class="form-control" name="password" formControlName="password" /> 
    <app-field-error-display [displayError]="formValidationService.IsFieldValid(_form,'password')" errorMsg="Please insert password"></app-field-error-display> 
</div> 
<button type="submit" class="btn btn-default">Create Account</button> 
</form> 
<div *ngIf="_registered" class="alert alert-success box-msg" role="alert"> 
    <strong>Account registered!</strong> You will be redirected in sec 
</div> 

コンポーネントを登録します。

ngOnInit() { 
    this._form = this._formBuilder.group({ 
     email: ['', [Validators.required, Validators.email]], 
     emailConfirm: ['', [Validators.required, Validators.email, MatchOtherValidator.Validate('email')]], 
     password: ['', [Validators.required]] 
    }); 

    this._registerModel = new RegisterModel(); 
} 

カスタムマッチ他のバリデータ:フォームコントロールが汚れや無効な場合

public IsFieldValid(form: FormGroup, field: string){ 
    return !form.get(field).valid && form.get(field).dirty; 
} 
+0

https://angular.io/guide/form-validation#built-in-validatorsを確認してください。 '* ngIf =" username.errors.minlength "'、 '* ngIf =" username.errors.required "' –

+0

はテンプレートに直接連結できません。 –

+0

最小長さのメッセージを表示する要素に最初の条件を置き、2番目の要素に必要なメッセージを表示します。私がリンクしているドキュメントに示されているように。具体的な問題は何ですか?あなたのコードはどこですか? –

答えて

3

あなたのコードのみチェック:

import { FormControl } from '@angular/forms'; 

export class MatchOtherValidator { 
    static Validate(otherControlName: string) { 

     let thisControl: FormControl; 
     let otherControl: FormControl; 

     return function matchOtherValidate(control: FormControl) { 

      if (!control.parent) { 
       return null; 
      } 

      // Initializing the validator. 
      if (!thisControl) { 
       thisControl = control; 
       otherControl = control.parent.get(otherControlName) as FormControl; 
       if (!otherControl) { 
        throw new Error('matchOtherValidator(): other control is not found in parent group'); 
       } 
       otherControl.valueChanges.subscribe(() => { 
        thisControl.updateValueAndValidity(); 
       }); 
      } 

      if (!otherControl) { 
       return null; 
      } 

      if (otherControl.value !== thisControl.value) { 
       return { 
        matchOther: true 
       }; 
      } 

      return null; 

     } 
    } 
} 

フォーム検証サービス、このメソッドを持っています。しかし、特定の検証に失敗したかどうかをチェックしたいとします。したがって、追加のerror引数( 'required'、 'minlength'など)を渡す必要があります。)、そして、カスタマーのバリデータmatchOtherはあなたが返す必要があります失敗した場合

form.get(field).hasError(error) 
+0

もう1つのこと、私はそれが表示されていないカスタムバリデータを持っている場合、私はプレビルダーバリデータを試してみました。私は 'MatchOtherValidator.Validate( 'email')]'メソッドを使用して、あなたはhasErrorでカスタムのバリデーターをチェックするのですか? –

+0

@AmelSalibasicお客様のバリデーターmatchOtherが失敗した場合は、{matchOther:true}を返し、form.get(field).hasError( 'matchOther');をチェックしてください。 –

1

を使用{matchOtherを:真}とform.get(field).hasError('matchOther');

関連する問題