2

I have tried this code for password pattern validation but it not works, tell me how to validate the pattern

HTML code:-

<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 file:-

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   
  }

When I enter data into the field, getting error Password Must Contain(4-20) 1-char! 1-number! which is

tag, but i need to validate the password like thi must contains 1 char 1 number,

Only entering Chars or Only entering number, the error message is displaying

2 Answers 2

3

Regex should be like this

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

(?=.*[A-Za-z]) - Assert a string has at least one Alphabet;

(?=.*\d) -Assert a string has at least one number;

[A-Za-z\d]{4,20} - Characters (Only numbers and letters) length should be between 4 and 20

Sign up to request clarification or add additional context in comments.

4 Comments

whether i could write in input field or ts file
If you want to use it in input, put pattern="/^(?=.[A-Za-z])(?=.\d)[A-Za-z\d]{4,20}$/". If you want to use inside ts, use as mentioned as above
I used in the ts file like this
Is it throwing any error or is it not working as expected? try using in input?
0

call it like this: Validators.pattern(/^(?=.[A-Za-z])(?=.\d)[A-Za-z\d]{4,20}/)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.