2017-01-23 81 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> 
相關問題