2017-01-23 74 views
-1

我需要检查用户输入的密码,如果它包含一个字母使其更强。如果密码只包含数字或字母,则应提示密码较弱且表单无效。这是我的代码。Validator检查密码是否至少包含1个字母或数字

ngOnInit(){ 
     this.registrationForm = this._formBuilder.group({ 
      password: ['', [Validators.required, Validators.minLength(8)]] 
     }); 
    } 

HTML代码

  <div class="form-group"> 
       <label for="password" class="cols-sm-2 control-label">Password</label> 
       <div class="cols-sm-10"> 
        <div class="input-group"> 
         <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span> 
         <input type="password" [(ngModel)]="user.password" class="form-control" name="password" id="password" placeholder="Enter your Password" formControlName="password"/> 
        </div> 
        <span *ngIf="registrationForm.controls.password.hasError('required') && registrationForm.get('password').touched" class="alert alert-danger">Password is required</span> 
        <span *ngIf="registrationForm.controls.password.hasError('minlength') && registrationForm.get('password').touched" class="alert alert-danger">Password should consist of 8 characters</span> 
       </div> 
      </div> 

编辑:我如何检查用户输入是否包含字母和数字,并返回弱密码,如果它仅包含数只或只信?

+0

这到底是什么问题?你所做的只是给我们一些小小的解释,你有没有问题?为什么这是一个问题?请编辑。 – pattyd

+0

编辑。增加了这个问题。谢谢 :) –

回答

0

我使用正则表达式解决了我的问题。

passwordRegex = /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/; 

这将检查密码是否至少包含一个字母或数字。然后在我的html中添加验证。

<span *ngIf="registrationForm.controls.password.hasError('pattern') && registrationForm.get('password').touched" class="alert alert-danger">Weak password</span> 
相关问题