确认密码验证程序不工作-Angular

确认密码验证程序不工作-Angular,angular,Angular,我试着做一个自定义验证器。如果密码不匹配,我想添加ng invalid类(将输入设置为invalid) 这是html- <div class="form-group"> <label for="password">Password:</label> <label class="validations" @load *ngIf="!regForm.get('password').valid && regForm.get('p

我试着做一个自定义验证器。如果密码不匹配,我想添加
ng invalid
类(将输入设置为invalid)

这是html-

<div class="form-group">
    <label for="password">Password:</label>
    <label class="validations" @load *ngIf="!regForm.get('password').valid && regForm.get('password').touched">Please Enter a Valid Password!</label>
    <input type="password" class="form-control" id="password" minlength="6" required placeholder="Enter Your Team Password" formControlName="password">
</div>
<div class="form-group">
      <label for="password">Confirm Password:</label>
      <label class="validations" @load *ngIf="(!(regForm.get('password').value == regForm.get('password_confirmation').value)) && regForm.get('password_confirmation').touched">Passwords do not Match!</label>
      <input type="password" class="form-control" id="password" 
          [ngClass]="{pwd_mismatch : !(regForm.get('password').value === regForm.get('password_confirmation').value) && regForm.get('password_confirmation').touched}" required placeholder="Re-Enter Your Team Password" formControlName="password_confirmation">
</div>
注意:
this.password
存储来自password
FormControl
的输入。
pwd\u不匹配
类实时添加到输入中,但未设置为无效

您的逻辑是反向的。如果密码匹配,即没有错误,则必须返回null。所以代码应该是

passwordConfirm(control: FormControl): {[s: string]: boolean} {
    if (control.value === this.password) {
        return null;
    }
    return { mismatch: true };
}

你的逻辑是颠倒的。如果密码匹配,即没有错误,则必须返回null。所以代码应该是

passwordConfirm(control: FormControl): {[s: string]: boolean} {
    if (control.value === this.password) {
        return null;
    }
    return { mismatch: true };
}

好的,现在可以了,但是即使输入了相同的密码,ng invalid也不会删除。密码可能不包含您认为它包含的内容。发布一个完整的最小示例来重现这个问题。明白了,现在我添加了-if(control.value==this.regForm.get('password').value),但它无法访问未定义的get。我让这个控件出现在FormGroup中-'password_confirmation':新的FormControl(null,this.passwordConfirm.bind(this)),再次,发布一个完整的最小示例,再现问题。好吧,现在可以了,但是即使输入了相同的密码,ng invalid也不会删除。密码可能不包含您认为它包含的内容。发布一个完整的最小示例来重现这个问题。明白了,现在我添加了-if(control.value==this.regForm.get('password').value),但它无法访问未定义的get。我让这个控件出现在FormGroup中-'password_confirmation':新的FormControl(null,this.passwordConfirm.bind(this)),再次,发布一个完整的最小示例,再现问题。