I am new to angular 5 ,Here I am trying to validate user password based on some conditions .
- Minimum six characters, at least one letter and one number
- Minimum eight characters, at least one letter, one number and one special character
- Minimum eight characters, at least one uppercase letter, one lowercase letter and one number
User can choose one of the above pattern for the password field the validation error message will change accordingly.
For me non of the above conditions are working correctly.
can anyone help me to solve this .
Note : if I give the pattern directly in HTML's it is working correctly
app.component.html
<mat-form-field class="col-sm-12">
<mat-label>Enter your password</mat-label>
<input matInput placeholder="Password" [pattern]="patternNormal" [formControl]="fPassword" placeholder="Password" required>
<mat-error *ngIf="fPassword.errors?.required">Please fill out this field</mat-error>
<mat-error *ngIf="fPassword.errors&&fPassword.errors.pattern">{{errorMgs}}</mat-error>
</mat-form-field>
app.component.ts
export class SnackBarOverviewExample {
//Minimum six characters, at least one letter and one number:
patternNormal: any = "^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$";
//Minimum eight characters, at least one letter, one number and one special character:
patternMedium: any = "^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$";
//Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:
patternHign: any = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}";
fEmail = new FormControl();
fPassword = new FormControl();
errorMgs: string;
selectedPattern: string;
constructor(private _formBuilder: FormBuilder) { }
ngOnInit() {
this.selectedPattern = 'patternNormal'; //will change based on user preference
if (this.selectedPattern === 'patternNormal') {
this.errorMgs = 'Password must have min 6 char,atleast 1 num and 1 char'
} else if (this.selectedPattern === 'patternMedium') {
this.errorMgs = 'Minimum eight characters, at least one letter, one number and one special character'
} else if (this.selectedPattern === 'patternHign') {
this.errorMgs = 'Minimum eight characters, at least one uppercase letter, one lowercase letter and one number'
}
}
Stackblitz URL :https://stackblitz.com/edit/angular-stacb4-5oaagd?file=app%2Fsnack-bar-overview-example.ts
Update :
1,sample value for first pattern - abcde1 (showing error but same value is accepted when I give the pattern directly in HTML).