2016-05-04 31 views
2

如何驗證密碼字段與正則表達式模式使用angular2而不使用formbuilder。使用angular2驗證輸入字段與正則表達式模式

我能夠驗證輸入字段的最大長度和最小長度,但以下使用正則表達式進行的驗證不起作用。

我試圖通過以下方式,但它不工作

<ion-item> 
    <ion-icon name="lock" item-left class="placeholder-icon"></ion-icon> 
    <ion-label floating primary>Password</ion-label> 
    <ion-input [(ngModel)]="login.password" 
     ngControl="password" type="password" #password="ngForm" 
     pattern="/^.*(?=.{6,})(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[[email protected]#$%^&*? ]).*$/"> 
    </ion-input> 
</ion-item>   
<p *ngIf="password.errors && password.errors.pattern" danger padding-left> 
    Password must contain one lowercase, one uppercase, one number, one 
    unique character such as [email protected]#$%^&? and be at least 6 characters long. 
</p> 
+0

或http://stackoverflow.com/questions/32314567/email-input-pattern-attribute –

回答

0

你需要實現一個自定義的指令應用/包裹Validators.pattern驗證。

下面是這個方法的實現:

const PATTERN_VALIDATOR = 
    new Provider(NG_VALIDATORS, {useExisting: forwardRef(() => PatternValidator), multi: true}); 

@Directive({ 
    selector: '[pattern][ngControl],[pattern][ngFormControl],[pattern][ngModel]', 
    providers: [PATTERN_VALIDATOR] 
}) 
export class PatternValidator implements Validator { 
    private _validator: Function; 

    constructor(@Attribute("pattern") pattern: string) { 
    this._validator = Validators.pattern(pattern); 
    } 

    validate(c: Control): {[key: string]: any} { return this._validator(c); } 
} 

您可以使用此指令是這樣的:

@Component({ 
    template: ` 
    (...) 
    <ion-input [(ngModel)]="login.password" ngControl="password" 
      type="password" #password="ngForm" 
      pattern="/^.*(?=.{6,})(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[[email protected]#$%^&*? ]).*$/"> 
    </ion-input> 
    (...) 
    `, 
    directives: [ PatternValidator ] 
}) 

這篇文章能吸引你:

相關問題