繁体   English   中英

模板驱动的“起始日期”和“截止日期”表单验证

[英]Template driven form validation for From Date and To Date

我正在尝试以模板驱动的形式添加对自日期和日期控件的验证。我如何验证它们,例如“自日期应该大于日期”,反之亦然。 我也想在整个应用程序中重用此验证,以用于不同的日期和日期控件。

因此,如果您使用临时模板驱动的表单,则在日期输入中会有一个ngModel。 为了进行验证,您可以检查日期模型的值并进行验证。 要知道您的模型是否更改,可以使用ngModelChange。

可以使用<>比较JS Date

 fromDate = new Date() // today toDate = new Date(fromDate.valueOf() + 60*60*24) // tomorrow function toDateIsLater(fromDate, toDate) { return toDate > fromDate } console.log(toDateIsLater(fromDate, toDate)) 

创建一个采用两个窗体控件的函数。 比较日期,并在出现错误时设置表单控件的错误:

compareDates(from: FormControl, to: FormControl) {
  const startDate: Date = ConvertYourFormValueToValidDate(from.value);
  const endDate: Date = ConvertYourFormValueToValidDate(to.value);

  if (startDate.getTime() > endDate.getTime()) {
    from.setErrors({ ...from.errors, 'aboveEnd': true });
  } else if (startDate.getTime() > endDate.getTime()) {
    to.setErrors({ ...to.errors, 'belowStart': true });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM