如何使用angular2使用正则表达式验证密码字段,而不使用formbuilder。
我能够验证输入字段的maxlength和minlength,但是使用正则表达式的以下验证不起作用。
我尝试了以下方式,但它无法正常工作
<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])(?=.*[!@#$%^&*? ]).*$/">
</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 !@#$%^&? and be at least 6 characters long.
</p>
答案 0 :(得分: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])(?=.*[!@#$%^&*? ]).*$/">
</ion-input>
(...)
`,
directives: [ PatternValidator ]
})
这篇文章让您感兴趣: