【发布时间】:2018-06-01 18:02:28
【问题描述】:
我来找你谈论有角材料的问题。其实我觉得是个问题,但我更喜欢先找个误会。
关于我的问题的第一件事是上下文,我尝试做一个包含两个输入的简单表单:密码及其确认。
user-form.component.ts
this.newUserForm = this.fb.group({
type: ['', Validators.required],
firstname: ['', Validators.required],
lastname: ['', Validators.required],
login: ['', Validators.required],
matchingPasswordsForm: this.fb.group(
{
password1: ['', Validators.required],
password2: ['', Validators.required],
},
{
validator: MatchingPasswordValidator.validate,
},
),
mail: ['', [Validators.required, Validators.pattern(EMAIL_PATTERN)]],
cbaNumber: [
'411000000',
[Validators.required, Validators.pattern(CBANUMBER_PATTERN)],
],
phone: ['', [Validators.required, Validators.pattern(PHONE_PATTERN)]],
}
我的兴趣是匹配PasswordsForm FormGroup。你可以在上面看到验证器。
这里是验证器:
matching-password.validator.ts
export class MatchingPasswordValidator {
constructor() {}
static validate(c: FormGroup): ValidationErrors | null {
if (c.get('password2').value !== c.get('password1').value) {
return { matchingPassword: true};
}
return null;
}
}
和 HTML。
user-form.component.html
<div class="row" formGroupName="matchingPasswordsForm">
<mat-form-field class="col-md-6 col-sm-12">
<input matInput placeholder="Mot de passe:" formControlName="password1">
<mat-error ngxErrors="matchingPasswordsForm.password1">
<p ngxError="required" [when]="['dirty', 'touched']">{{requiredMessage}}</p>
</mat-error>
</mat-form-field>
<mat-form-field class="col-md-6 col-sm-12">
<input matInput placeholder="Confirmez" formControlName="password2">
<mat-error ngxErrors="matchingPasswordsForm.password2">
<p ngxError="required" [when]="['dirty', 'touched']">{{requiredMessage}}</p>
</mat-error>
<!-- -->
<!-- problem is here -->
<!-- -->
<mat-error ngxErrors="matchingPasswordsForm" class="mat-error">
<p ngxError="matchingPassword" [when]="['dirty', 'touched']">{{passwordMatchErrorMessage}}</p>
</mat-error>
<!-- ^^^^^^^^^^^^^^^^ -->
<!-- /problem is here -->
<!-- -->
</mat-form-field>
</div>
我已经用 cmets 包围了有趣的代码。
现在,一些解释:使用标签,当触摸密码2时,会显示我的错误:
但是,当我输入错误的密码时,不再显示错误:
首先我以为我误解了自定义验证器的使用。但是当我用整个东西替换时,效果很好!
用提示替换错误
<mat-hint ngxErrors="matchinghPasswordsForm">
<p ngxError="matchingPassword" [when]="['dirty', 'touched']">{{passwordMatchErrorMessage}}</p>
</mat-hint>
我希望我是清楚的,我真的很想在材料设计 github 上发布问题之前得到你的观点。
如果我误解了什么,请点燃我错过的东西。
最后一件事,我的测试是使用 ngxerrors 和 *ngif 完成的。为了更具可读性,我的代码示例仅使用 ngxerrors 。
提前感谢您抽出宝贵的时间。
【问题讨论】:
-
@AJT_82 :就像在回答您的链接时所说的那样,如果您更改了前日期,则不再显示错误消息,问题似乎和我的一样
-
是的,因此制作一个错误状态匹配器;)
标签: angular angular-material2 custom-validators