我正在尝试使用new password
验证典型的confirm password
和Angular Directive
匹配。即使指令正确捕获不匹配,也不会显示错误消息:
模板表单
<form>
<md-input-container class="signup-full-width">
<input
mdInput
autocomplete="off"
type="password"
name="password"
#currentPasswd="ngModel"
placeholder="Current password"
[(ngModel)]="currentPassword"
required>
<md-error *ngIf="currentPasswd.errors && (currentPasswd.dirty || currentPasswd.touched)" [ngStyle]="{'color': 'red'}">
<div [hidden]="!currentPasswd.errors.required">Required</div>
</md-error>
</md-input-container>
<div ngModelGroup="passwordGroup" password-matcher #passwordGroup="ngModelGroup">
<md-input-container class="signup-full-width">
<input
mdInput
autocomplete="off"
type="password"
name="newPassword"
#newPasswd="ngModel"
placeholder="New password"
[(ngModel)]="newPassword"
required
minlength="8"
maxlength="15">
<md-error *ngIf="newPasswd.errors && (newPasswd.dirty || newPasswd.touched)" [ngStyle]="{'color': 'red'}">
<div [hidden]="!newPasswd.errors.required">Required</div>
<div [hidden]="!newPasswd.errors.minlength">Must be at least 8 characters</div>
<div [hidden]="!newPasswd.errors.maxlength">Must be at most 15 characters</div>
</md-error>
</md-input-container>
<md-input-container class="signup-full-width">
<input
mdInput
autocomplete="off"
type="password"
name="confirmPassword"
placeholder="Confirm password"
[(ngModel)]="confirmPassword">
<md-error *ngIf="passwordGroup.control?.errors" [ngStyle]="{'color': 'red'}">
<div [hidden]="!passwordGroup.control.errors.noMatch">Passwords do not match</div>
</md-error>
</md-input-container>
</div>
<p>passwordGroup.control?.errors: {{passwordGroup.control?.errors | json}}</p>
</form>
请注意ngModelGroup
周围的'新密码'和'确认密码'字段div
。
密码指令 Angular 2 Forms | Kara Erickson
function passwordMatcher(c: AbstractControl) {
if (!c.get("newPassword") || !c.get("confirmPassword")) return null;
return c.get("newPassword").value === c.get("confirmPassword").value
? null : {"noMatch": true};
}
@Directive({
selector: '[password-matcher]',
providers: [
{provide: NG_VALIDATORS, multi: true, useValue: passwordMatcher}
]
})
export class PasswordMatcher {
}
但是,“确认密码”输入中永远不会显示所需的错误消息。即使该指令似乎在调试输出中显而易见:
答案 0 :(得分:0)
在您的代码中,您有:
<input #newPasswd="ngModel" ... [(ngModel)]="newPassword" >
我在卡拉的视频中注意到@ 18:13它看起来像这样:
<input ngModel name="password" ... #password="ngModel"
&GT;
尝试将这两个地方的代码更改为此语法/序列,看看是否可以修复它。
提示:这是因为newPasswd是您的语法必然需要的指令。
您正在使用名称中的newPassword,而不是#Angular模板变量。