自定义验证:密码确认
Mustafa是对的,当你使用角material 和mat-error
个标签时,最好使用react 形式.但是,这里有一个更完整的版本,包括所有验证消息,因为您需要'A LOT OF'帮助.
我也改进了Mustafa的验证器.这将帮助您消除验证消息的所有奇怪之处.
可见性图标逻辑已删除,因为material 密码输入已内置此功能.
脚本:
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group(
{
password: [
'',
[
Validators.required,
Validators.minLength(8),
Validators.maxLength(100),
],
],
confirmPassword: [
'',
[
Validators.required,
Validators.minLength(8),
Validators.maxLength(100),
],
],
},
{ validator: CustomValidators.MatchingPasswords }
);
}
改进的自定义验证器:
export class CustomValidators {
static MatchingPasswords(control: AbstractControl) {
const password = control.get('password').value;
const confirmPassword = control.get('confirmPassword').value;
const currentErrors = control.get('confirmPassword').errors
const confirmControl = control.get('confirmPassword')
if (compare(password, confirmPassword)) {
confirmControl.setErrors({...currentErrors, not_matching: true});
} else {
confirmControl.setErrors(currentErrors)
}
}
}
function compare(password: string,confirmPassword: string) {
return password !== confirmPassword && confirmPassword !== ''
}
模板:
<form [formGroup]="form">
<mat-form-field>
<mat-label>Password</mat-label>
<input
matInput
type="password"
placeholder="Password"
formControlName="password"
/>
<mat-error *ngIf="form.get('password').hasError('required')">
Password is required!
</mat-error>
<mat-error *ngIf="form.get('password').hasError('minlength')">
Password should be longer than 8 characters!
</mat-error>
<mat-error *ngIf="form.get('password').hasError('maxlength')">
Password can't be longer than 100 characters!
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Confirm Password</mat-label>
<input
matInput
placeholder="Confirm your password..."
formControlName="confirmPassword"
type="password"
/>
<mat-error *ngIf="form.get('confirmPassword').hasError('required')">
Password confirmation is required!
</mat-error>
<mat-error *ngIf="form.get('confirmPassword').hasError('minlength')">
Password should be longer than 8 characters!
</mat-error>
<mat-error *ngIf="form.get('confirmPassword').hasError('maxlength')">
Password can't be longer than 100 characters!
</mat-error>
<mat-error *ngIf="form.get('confirmPassword').hasError('not_matching')">
The password doesn't match!
</mat-error>
</mat-form-field>
</form>
You can clean up all the 100 tags, by providing the message with a function.
这里有一个关于Stackblitz的例子供您使用.