Angular. Некорректно работает валидатор для поля проверки пароля
Подскажите пожалуйста, где я ошибся. Написал кастомный валидатор для проверки пароля, но работает он не так как я задумал. Ожидал, что при вводе в поле Confirm password пароль будет невалиден, если пароли не совпадают. Но выходит, что поле Сonfirm password валидно при вводе абсолютно любого символа.
app.component.ts
ngOnInit(): void {
this.form = new FormGroup({
//...
password: new FormControl('', [
Validators.required,
Validators.minLength(5),
Validators.pattern(/^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^#$_\-+!]*[#$_\-+!]).{5,}$/),
]),
confirmPassword: new FormControl('', [
Validators.required,
]),
}, {validators: this.passwordMatchValidator});
}
passwordMatchValidator(form: FormGroup) {
return form.value.password === form.value.confirmPassword ? null : { mismatch: true};
}
app.component.html
div class="container">
<form class="auth-form"
[formGroup]="form" (ngSubmit)="submit()">
<h1>Registration new User</h1>
<div class="form-control">
<label>Password:
<input class="form-input" type="password" name="password"
formControlName="password"
pattern="^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^#$_\-+!]*[#$_\-+!]).{5,}$">
</label>
<div *ngIf="form.get('password').invalid && form.get('password').touched"
class="validation">
<small *ngIf="form.get('password').errors.required">
The password field is required. </small>
<small *ngIf="form.get('password').errors.minlength">
The password must be at least {{form.get('password').errors.minlength["requiredLength"]}} characters.
</small>
<br>
<small *ngIf="form.get('password').errors.pattern">
The password must include uppercase and lowercase letters, numbers, and one of symbols: '_' '!' '#' '+' '-' '$'
</small>
</div>
</div>
<div class="form-control">
<label>Confirm password:
<input class="form-input" type="password" name="confirmPassword" formControlName="confirmPassword"></label>
<div *ngIf="form.get('confirmPassword').invalid && form.get('confirmPassword').touched"
class="validation">
<small *ngIf="form.get('confirmPassword').errors.required">
The Confirm Password field is required.
</small>
<small *ngIf="form.errors || form.get('confirmPassword').errors.mismatch">
Password doesn't match.
</small>
</div>
</div>
<button class="btn" type="submit">Submit</button>
ссылка на stackblitz https://stackblitz.com/edit/angular-bvrnrf?embed=1&file=src/app/app.component.ts
Ответы (1 шт):
Автор решения: user377826
→ Ссылка
Я решил сделать C реактивной формой Angular и как советуют с FormBuilder Вот код:
export class RegistrationComponent implements OnInit {
formReg: FormGroup;
constructor(private fb: FormBuilder, private authService: AuthService { this._createForm(); }
private _createForm() {
this.formReg = this.fb.group({
username: ['', [
Validators.required,
Validators.minLength(2),
Validators.pattern('[A-Za-z0-9]*')
]],
password: [
'',
[ Validators.required,
Validators.minLength(3),
Validators.pattern('[A-Za-z0-9]*')
]
]
});
}
get _username() {return this.formReg.get('username'); }
get _password() {return this.formReg.get('password'); }
ngOnInit() {...}
и мой html
<form [formGroup]="formReg" >
<div class="form-group">
<label for="username">username </label>
<input type="username" name="username" id="username" formControlName="username" class="form-control"
aria-describedby="usernameHelp" placeholder="Enter username" required>
<br><small id="usernameHelp" class="form-text text-muted">you username account</small>
<div *ngIf="_username.invalid && (_username.dirty || _username.touched)" class="alert alert-danger"></div>
<div *ngIf="_username.errors?.required">Обязательное поле</div>
<div *ngIf="_username.errors?.minlength">Введите не менее 2 символов</div>
<span *ngIf="_username.errors?.pattern">Неразрешенные символы</span>
</div>
тоже самое и для password