Reputation: 169
I have a password field.Added validation in that like it allows all the characters except white space.
Let me show the code below what I'm using:
org-user.component.html
<div class="form-group cav-form" [ngClass]="{'has-danger':!OrgUserForm.controls['password'].valid
&& !OrgUserForm.controls['password'].untouched}">
<label for="password">Password</label>
<span *ngIf="!OrgUserForm.controls['password'].valid ">*</span>
<input type="password" (keypress)="restrictNumeric($event)" class="form-control" id="password" [(ngModel)]="formdata.password" formControlName="password" placeholder="Enter Password">
</div>
org-user.component.ts
public restrictNumeric(e) {
let input;
if (e.metaKey || e.ctrlKey) {
return true;
}
if (e.which === 32) {
return false;
}
input = String.fromCharCode(e.which);
}
What I want to do exactly here is I need validation according to what type of character user misses while entering password.
For Example: when typing something like "Welcome123" in this case user missed a "special character" so want to display message like "special character missed".
In short I want to display validation message dynamically according to the attributes missed in the password field.
Does anyone have an idea on how to do this?
Thanks in advance!
Upvotes: 1
Views: 937
Reputation: 24444
If you validation is complex and you want to be in control of the message you can write custom validator that test all cases you want and return a desire message.
password strength validator
import { AbstractControl, ValidationErrors } from "@angular/forms";
export const PasswordStrengthValidator = function (
control: AbstractControl
): ValidationErrors | null {
let value: string = control.value || "";
if (!value) {
return null;
}
let upperCaseCharacters = /[A-Z]+/g;
if (upperCaseCharacters.test(value) === false) {
return {
passwordStrength: `text has to contine Upper case characters,current value ${value}`
};
}
let lowerCaseCharacters = /[a-z]+/g;
if (lowerCaseCharacters.test(value) === false) {
return {
passwordStrength: `text has to contine lower case characters,current value ${value}`
};
}
let numberCharacters = /[0-9]+/g;
if (numberCharacters.test(value) === false) {
return {
passwordStrength: `text has to contine number characters,current value ${value}`
};
}
let specialCharacters = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
if (specialCharacters.test(value) === false) {
return {
passwordStrength: `text has to contine special character,current value ${value}`
};
}
return null;
};
Upvotes: 1