【问题标题】:I don't get the return of cross-validation to template-driven forms我没有将交叉验证返回到模板驱动的表单
【发布时间】:2022-01-10 20:47:54
【问题描述】:

我正在尝试让true 在密码不同时返回。

我的组件

this.restrict = new FormGroup({
  email: new FormControl(this.user.email),
  newPassword: new FormControl ('', [Validators.required, Validators.pattern('(?=\\D*\\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z]).{6,30}')]),
  confirmPassword: new FormControl(null, [Validators.required, Validators.minLength(6)]),
}, {validators: this.pwdMatchValidator});

get newPassword() { return this.restrict.get('newPassword');}
get confirmPassword() { return this.restrict.get('confirmPassword');}

pwdMatchValidator(frm: FormGroup) {
  let pass = frm.get('newPassword').value;
  let confirmPass = frm.get('confirmPassword').value;
  console.log(pass);
  console.log(confirmPass);
  return pass === confirmPass ? null: { notSame: true};
}

在我的模板中

<p-password formControlName="confirmPassword"></p-password>
<small class="p-error" *ngIf="confirmPassword.hasError('required')">No puede estar vacio</small>
<small class="p-error" *ngIf="confirmPassword.hasError('minlength')">Debe ser de hasta 6 caracteres.</small>
<small class="p-error" *ngIf="confirmPassword.hasError('notSame', 'passwords')">Las contraseñan son diferentes.</small>
<button pButton pRipple label="Save" icon="pi pi-check" class="p-button-text" [disabled]="!restrict.valid"></button>

目前我得到的答案总是false

concole.log(pass);console.log(confirmPass); 是否有效并且保存按钮仍然被禁用,因为该字段未经过验证,那么我怎样才能获得 notSame?我试过了:

{{ restrict.get('confirmPassword').errors?.notSame }}
{{ restrict.get('confirmPassword').errors }}
{{ confirmPassword.hasError('notSame') }}

在角度 examples 中,它们显示的形状在我的情况下(角度 12)不起作用

在 Angular 文档中,我找不到一个令人满意的关于如何处理退货的概念,请您解释一下吗?

【问题讨论】:

    标签: angular typescript validation primeng


    【解决方案1】:

    您的验证器设置在 FormGroup 而不是 confirmPassword 表单控件上,因此您需要做的检查实际上是在 parentForm 上:

    <small ngIf="restrict.hasError('notSame')">...</small>
    

    STACKBLITZ

    【讨论】:

    • 感谢回答,那么交叉验证时返回的总是parentForm?还是有一些特征将其定位为 parentForm?
    • 你已经把你的验证器放在了父节点上 => this.restrict = new FormGroup({ }, {validators: this.pwdMatchValidator});
    • 最简单的是,如果你想执行交叉验证,我会说 parentform 或嵌套 parentform 将是要走的路,否则你需要向上遍历以获得要比较的其他控件和。如果您将验证器设置为例如 confirmPassword,那么您将需要遍历父级以获取密码表单控件。
    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多