2017-06-24 47 views
1

我使用FormBuilder方法制作了一個表單。現在我想添加一些模式驗證。如何在控件失去焦點時顯示模式驗證錯誤 - Angular 2

我添加了驗證,它工作正常。但驗證錯誤顯示在非期望的時間。

我已添加一個textfield並添加了pattern驗證。我想在另一個控件被選中或失去焦點時顯示錯誤消息。 但是,當我開始輸入文本時,目前顯示驗證錯誤。

我可以在丟失焦點事件中顯示錯誤消息嗎?我知道我可以通過綁定onChange事件TextControl中的一種方法來輕鬆地做到這一點,但如果有另一種方法,我很樂意知道這一點。

Here is the Plnkr

回答

1

是的,你可以做到這一點認購於特定的一個控制valuechanges valuechange。

實施例 **

第一方法

import... 
    @Component({..}) 
    export class ExampleComponent implements OnInit { 

     ngOnInit(): void { 
       this.formName.get('name') 
        .valueChanges 
        .filter((value: string) => value != null && value.length > 0) // use filter if needed otherwise remove it 
        .subscribe((value: string) => { 
         if (!value.match(/[-!$%^&*(/]/... set here your pettern)) { 
            this.formName.controls.name.setErrors({}); 
          } 
        } 

      } 
     } 

第二方法

在組件

HTML

<input type='text' (blur)="checkValidation()" formControlName="name"> 

{{的errorMessage}}

方法

import... 
    @Component({..}) 
    export class ExampleComponent implements OnInit { 
    errorMessage =''; 
     ngOnInit(): void { 

      } 

     checkValidation(): void { 
      if (!value.match(/[-!$%^&*(/]/... set here your pettern)) { 
       this.formName.controls.name.setErrors({}); 
       this.errorMessage = 'set here your message'; 
       } 
     } 
+0

是的,我知道這個方法。我對'blur'事件感興趣。如何在控件失去焦點時顯示錯誤消息@Shalesh – Dalvik

+0

好的,我更新我的答案等待 –

+0

請檢查。更新 –