【问题标题】:how can I compare values of two fields for validation in angular 2+ formbuilder如何在 Angular 2+ formbuilder 中比较两个字段的值以进行验证
【发布时间】:2018-03-21 19:13:47
【问题描述】:

我正在学习 angular ionic,目前正在尝试使用 angular 表单、FormGroup 和 FormBuilder 功能来验证一些表单数据。

我有四个字段要相互验证,但我不知道如何编写一个可以查看其他字段值的验证器。

相关字段为:

startDate, startTime, endDate, endTime.

因为这些是离子日期时间输入,所以它们总是采用“ISO 8601”格式。所以示例值可能是:

startDate: "2018-03-28"
startTime: "18:52"

我的目标是验证其中的每一个,以便在开始时间和日期早于结束时间和日期的情况下它们是有效的。例如,所有四个字段在以下情况下均有效:

startDate is "2018-03-28",
startTime is "14:30",
endDate is "2018-03-28", and
endTime is "18:00"

并且所有四个字段都无效时,例如:

startDate is "2018-03-28",
startTime is "14:30",
endDate is "2018-02-24", and
endTime is "23:00"

如何使用角形特征来比较这些字段的值?

任何帮助将不胜感激!

【问题讨论】:

标签: angular validation angular2-formbuilder


【解决方案1】:

解决方案是创建一个子 FormGroup 并将其嵌套在主 FormGroup 中(使用 FormBuilder)。

我的 .ts 文件中的代码如下所示:

  this.timingSubForm = new FormGroup({
    startDate: new FormControl('', Validators.compose([Validators.required])),
    startTime: new FormControl('', Validators.compose([Validators.required])),
    endDate: new FormControl('', Validators.compose([Validators.required])),
    endTime: new FormControl('', Validators.compose([Validators.required]))
  },
    (formGroup: FormGroup) => {
      return TimeValidator.validateTimes(formGroup);
    }
  );


  this.createItemForm = formBuilder.group({
    itemTitle:  ['', Validators.compose([Validators.minLength(4),Validators.maxLength(100), Validators.required])],
    itemDescription: ['', Validators.compose([Validators.minLength(10),Validators.maxLength(10000), Validators.required])],
    timingSubForm: this.timingSubForm
  });

模板文件如下所示:

<form [formGroup]="createItemForm">
    .. some input fields ..
    <div formGroupName="timingSubForm">
        .. date specific input fields ..
    </div>
    .. some more input fields ..
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多