Angular反应形式验证器中的密码验证错误

时间:2018-08-19 12:22:43

标签: javascript regex angular validation angular-reactive-forms

使用Angular反应形式来验证密码,以使密码与至少一个匹配:

|*> 1 lowercase
|*> 1 uppercase
|*> 1 numeric
|*> 8 char longer

使用Reg Exp:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})"

HTML代码:

<form [formGroup]="NamFomNgs">

    <label>Email : 
        <input type="email" name="MylHtm" formControlName="MylNgs">
    </label><br>
        <div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['MylNgs'].touched || NamFomNgs.controls['MylNgs'].dirty) && 
            !NamFomNgs.controls['MylNgs'].valid">
            <span *ngIf="NamFomNgs.controls['MylNgs'].errors.required">This field is required</span>
            <span *ngIf="NamFomNgs.controls['MylNgs'].errors.email">Enter valid email</span>
        </div><br>

    <label>Password : 
        <input type="text" name="PwdHtm" formControlName="PwdNgs">
    </label><br>
        <div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['PwdNgs'].touched || NamFomNgs.controls['PwdNgs'].dirty) && 
            !NamFomNgs.controls['PwdNgs'].valid">
            <span *ngIf="NamFomNgs.controls['PwdNgs'].errors.required">This field is required</span>
            <span *ngIf="NamFomNgs.controls['PwdNgs'].errors.pattern">Enter valid password</span>
        </div><br>

    <button [disabled]="!NamFomNgs.valid">Submit</button>
</form>

TypeScript代码:

NamFomNgs:FormGroup;

constructor(private NavPkjVaj: ActivatedRoute, private HtpCncMgrVaj: HttpClient,private FomNgsPkjVaj: FormBuilder){

    this.NamFomNgs = FomNgsPkjVaj.group(
        {
            MylNgs:[null,Validators.compose([
                Validators.required,
                Validators.email ])],
            PwdNgs:[null,Validators.compose([
                Validators.required,
                Validators.pattern("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})")])]
        });
}

输出的屏幕截图: enter image description here

当我尝试使用https://regex101.com/

相同的reg exp显示对要求有效。但是它在Angular中无效。请以正确的方式帮助我并解决此问题。

1 个答案:

答案 0 :(得分:2)

您必须在正则表达式中捕获某些内容,而只是使用积极的前瞻性组。只需像这样更改长度部分:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"