I am using a reactive form in angular 6, and trying to do some validation on a password field. Basically it needs to be more than 8 characters, contain at least 1 upper case, and contain at least 1 symbol.
my regex which I have tested, is ^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})
Here is an excerpt from my login component ts:
ngOnInit() {
this.loginForm = this.formBuilder.group({
userName: ['Username', [Validators.required]],
password: ['Password', [Validators.pattern("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})")]]
});
}
Here is my form group div:
<div class="form-group">
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.pattern">Password must contain more than 8 characters, 1 upper case letter, and 1 special character</div>
</div>
</div>
Basically the password does not validate even if it appears to be correct. Any tips would be appreciated.
Pattern Validation with formControl username = new FormControl(); In HTML template we will use Angular pattern attribute with regex in following way. We can bind component property with pattern using Angular property binding. Suppose we have following component property for regex to validate user name.
ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }
The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value.
Either first use “clearValidators()” to remove all validators and then use “setValidators()” to set needed validation. Or directly use “setValidators()” with the needed validators only (without the validator you don't want to have).
ng-pattern seem to take a regExp as parameter (like in angularJs) :
Validators.pattern(new RegExp("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,}))")
You can also use /..../
Validators.pattern(/^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})/)
Should work ;)
I think it's due to the *ngIf
condition in your HTML.]
Try *ngIf="loginForm.controls.password.hasError('pattern')"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With