我已经尝试了密码模式验证的代码,但它不起作用,请告诉我如何验证模式
HTML代码: -
<form [formGroup]="myForm" (ngSubmit)="submit()" >
<ion-item>
<ion-label primary floating>PASSWORD</ion-label>
<ion-input type="password" id="password" class="form-control" formControlName="password" minlength="4" maxlength="20" required></ion-input>
</ion-item>
<p *ngIf="myForm.controls.password.errors && myForm.controls.password.dirty ">
<small class="up"><strong><i>Password Must Contain(4-20) 1-char! 1-number!</i></strong></small></p>
</form>
ts文件: -
export class SinupPage {
myForm: FormGroup
passwordRegex: any = '((?=.*\d)(?=.*[a-zA-Z]).{4,20})' ;
this.myForm = formBuilder.group({
'password' : new FormControl('',Validators.compose([Validators.required,Validators.minLength(4), Validators.maxLength(20),Validators.pattern(this.passwordRegex]))
}
submit(){
let registerNewUserObj ={
password:this.myForm.value.password
}
当我在字段中输入数据时,收到错误密码必须包含(4-20)1-char! 1号!是
标签,但我需要验证密码,例如必须包含1个char 1号码,
仅输入字符或仅输入数字,显示错误消息
答案 0 :(得分:1)
正则表达式应该是这样的
/ ^(?=。* [A-ZA-Z])(?=。* \ d)[A-ZA-Z \ d] {4,20} /
(?=.*[A-Za-z])
- 断言字符串至少有一个字母;
(?=.*\d)
- 断言一个字符串至少有一个数字;
[A-Za-z\d]{4,20}
- 字符(仅限数字和字母)长度应在4到20之间
答案 1 :(得分:0)
这样称呼:Validators.pattern(/^(?=.[A-Za-z])(?=.\d)[A-Za-z\d]{4,20}/)