【问题标题】:Password Validation Pattern in angular 2角度 2 中的密码验证模式
【发布时间】:2016-12-16 06:33:43
【问题描述】:

我已尝试使用此代码进行密码模式验证,但它不起作用,请告诉我如何验证模式

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   
  }

当我在字段中输入数据时,出现错误 Password Must Contain(4-20) 1-char! 1 个数字!

标签,但我需要验证密码,例如 thi 必须包含 1 个字符 1 个数字,

只输入字符或只输入数字,显示错误信息

【问题讨论】:

    标签: angular forms validation


    【解决方案1】:

    正则表达式应该是这样的

    /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{4,20}/

    (?=.*[A-Za-z]) - 断言一个字符串至少有一个字母;

    (?=.*\d) - 断言一个字符串至少有一个数字;

    [A-Za-z\d]{4,20} - 字符(仅限数字和字母)长度应在 4 到 20 之间

    【讨论】:

    • 我是否可以在输入字段或ts文件中写入
    • 如果你想在输入中使用它,把 pattern="/^(?=.[A-Za-z])(?=.\d)[A-Za-z\d ]{4,20}$/"。如果要在ts内部使用,如上所述使用
    • 我在ts文件中这样使用
    • 它是抛出任何错误还是没有按预期工作?尝试在输入中使用?
    【解决方案2】:

    这样称呼它:Validators.pattern(/^(?=.[A-Za-z])(?=.\d)[A-Za-z\d]{4,20}/)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2020-10-10
      • 2018-06-29
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多