2017-09-26 157 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很多这是工作:) –

相关问题