【问题标题】:Cross field Validation in AngularAngular中的跨字段验证
【发布时间】:2020-07-06 15:02:10
【问题描述】:

我创建了下面的指令来创建跨领域验证遵循英雄之旅示例https://angular.io/guide/form-validation

这是我的代码:

import { ValidatorFn, FormGroup, ValidationErrors } from "@angular/forms";

export const ConsentReceivedValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => 
{
    const idNumber = control.get("idNumber");
    const consent = control.get("consentConfirmed");

    return idNumber && consent && idNumber.value !== null && consent.value === true ? { 
   "ConsentReceived": true } : null;
};

但是我得到以下错误:

Type '(control: FormGroup) => ValidationErrors | null' is not assignable to type 'ValidatorFn'.

这是在 html 中验证错误的方式:

    <div>
        <app-text-input-with-label labelText="ID Number" formControlItemName="idNumber"
            [form]="contactInformationForm">
        </app-text-input-with-label>
        <app-checkbox-with-label [labelText]="getConsentText()" checkboxItemName="consentConfirmed"
            [isContactInfo]="true" [form]="contactInformationForm">
        </app-checkbox-with-label>
        <div *ngIf="contactInformationForm.errors?.consentReceived"
            class="alert alert-danger alert-sm text-left mt-1">
            Please read and tick the box before proceeding.
        </div>
        <br>
        <app-reference-input [form]="contactInformationForm"></app-reference-input>
    </div>
</div>   

【问题讨论】:

  • 只需删除 : ValidatorFn 即可。
  • 这行得通,谢谢。

标签: html angular typescript angular-directive angular-validation


【解决方案1】:
export const ConsentReceivedValidator: ValidatorFn = () => (control: FormGroup): ValidationErrors | null => 
{
    const idNumber = control.get("idNumber");
    const consent = control.get("consentConfirmed");

    return idNumber && consent && idNumber.value !== null && consent.value === true ? { 
   "ConsentReceived": true } : null;
};

验证器函数如下所示。你需要像这样使用它:

[ConsentReceivedValidator()]

或者只是删除打字,你可以使用它而不调用它。

【讨论】:

  • 该错误是实际指令的编译错误,而不是在尝试使用它时。
  • 我将编辑我的问题以显示如何验证错误,也许您可​​以扩展您的解决方案来解决这个问题?
猜你喜欢
  • 2019-03-24
  • 1970-01-01
  • 2023-03-23
  • 2020-08-24
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
相关资源
最近更新 更多