Leo*_*mes 3 forms angular-material angular angular-reactive-forms
我希望得到你的很多帮助。我无法在版本 12 中使用 Angular 材料验证密码字段并确认密码。我在 html 中使用下面的结构。
<div>
<mat-form-field>
<mat-label>Password</mat-label>
<input matInput
type="password"
placeholder="Digite sua senha"
[type]="hide ? 'password' : 'text'"
[formControl]="passwordFormControl" />
<mat-icon matSuffix (click)="hide = !hide">
{{ hide ? 'visibility' : 'visibility_off' }}
</mat-icon>
<mat-error>
</mat-error>
</mat-form-field>
</div>
<div>
<mat-form-field>
<mat-label>Confirm Password</mat-label>
<input matInput
type="password"
placeholder="Digite novamente sua senha"
[type]="hide ? 'password' : 'text'"
[formControl]="passwordFormControl"/>
<mat-icon matSuffix (click)="hide = !hide">
{{ hide ? 'visibility' : 'visibility_off' }}
</mat-icon>
<mat-error>
</mat-error>
</mat-form-field>
</div>
Run Code Online (Sandbox Code Playgroud)
您可以使用反应式表单来验证。这就是您形成结构的方式,在这里您可以处理其他样式和所有内容
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
constructor(
private fb: FormBuilder,
....rest
) { }
this.form=this.fb.group({
.... other enteries
password: ['', Validators.compose([
Validators.required,
Validators.minLength(8),
Validators.maxLength(100)
])
],
confirmPassword: ['', Validators.compose([
Validators.required,
Validators.minLength(8),
Validators.maxLength(100)
])
},{ validator: ConfirmPasswordValidator.MatchPassword})
Run Code Online (Sandbox Code Playgroud)
这就是你的验证器的样子
import { AbstractControl } from '@angular/forms';
export class ConfirmPasswordValidator {
/**
* Check matching password with confirm password
* @param control AbstractControl
*/
static MatchPassword(control: AbstractControl) {
const password = control.get('password').value;
const confirmPassword = control.get('confirmPassword').value;
if (password !== confirmPassword) {
control.get('confirmPassword').setErrors({ConfirmPassword: true});
} else {
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3502 次 |
| 最近记录: |