2017-09-26 169 views
0

我試圖表現出從使用角度材料md-error指令自定義錯誤消息,所以我寫了,下面的方法:顯示自定義錯誤消息2

打字稿文件

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

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

    nicFormControl = new FormControl('', [ 
    Validators.required, 
    validateNICInput ]); 

} 

// custom error checking 
function validateNICInput(c: FormControl) { 

    let NIC_REGEX_OLD = /(^\d{9}[V|v|x|X]$)/; // Regular Expression 1 
    let NIC_REGEX_NEW = /[0-9]{12}$/;   // Regular Expression 2 

    var old_statement = NIC_REGEX_OLD.test(c.value); 
    var new_statement = NIC_REGEX_NEW.test(c.value); 

    return (old_statement || new_statement) ? true : { 
      validateInput: { 
       valid: false 
      } 
     }; 
} 

HTML文件

<form class="example-form"> 
    <md-form-field class="example-full-width"> 
    <input mdInput placeholder="NIC" [formControl]="nicFormControl"> 
    <md-error *ngIf="nicFormControl.hasError('required')"> 
     NIC is <strong>required</strong> 
    </md-error> 
    <md-error *ngIf="validateNICInput"> 
     Please enter a valid NIC 
    </md-error> 
    </md-form-field> 
</form> 

Plunker

在上面的代碼段中,我試圖顯示自定義錯誤消息使用*ngIf="validateNICInput",特定於無效輸入

但是,如果我輸入無效值,上述方法不起作用。輸入的下劃線變爲紅色,並且不顯示錯誤文本Please enter a valid NIC

下面是我嘗試其他方法,但至今未能:

方法2

<form class="example-form"> 
    <md-form-field class="example-full-width"> 
    <input mdInput placeholder="NIC" [formControl]="nicFormControl"> 
    <md-error *ngIf="nicFormControl.hasError('required')"> 
     NIC is <strong>required</strong> 
    </md-error> 
    <md-error *ngIf="nicFormControl.validateNICInput"> 
     Please enter a valid NIC 
    </md-error> 
    </md-form-field> 
</form> 

方法3

<form class="example-form"> 
    <md-form-field class="example-full-width"> 
    <input mdInput placeholder="NIC" [formControl]="nicFormControl"> 
    <md-error *ngIf="nicFormControl.hasError('required')"> 
     NIC is <strong>required</strong> 
    </md-error> 
    <md-error *ngIf="nicFormControl.hasError(validateNICInput)"> 
     Please enter a valid NIC 
    </md-error> 
    </md-form-field> 
</form> 

但沒有其他辦法的上方工作。

回答

1

驗證器返回錯誤。改用此聲明:

Typescript

return (old_statement || new_statement) ? true : { invalidNIC: true }; 

HTML

<md-error *ngIf="nicFormControl.hasError('invalidNIC')"> 
    Please enter a valid NIC 
</md-error> 

Plunker

+0

日Thnx很多這是工作:) –

相關問題