You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何验证选中日期与日期数组是否存在连续日期

Angular Reactive Forms 连续日期验证实现

场景说明

假设从输入框选中了01/01/2022,现有日期数组如下:

['31/12/2021', '01/11/2021', '02/01/2022'...] 

由于*'31/12/2021'(前一天)和'02/01/2022'*(后一天)是选中日期的连续日期,需要触发表单验证并抛出错误。

实现步骤

1. 日期连续判断工具函数

先写一个工具函数,用来检测两个日期是否为连续的前/后一天:

// 判断两个DD/MM/YYYY格式的日期是否为连续日期
const isConsecutiveDate = (selectedDate: string, arrayDate: string): boolean => {
  // 解析DD/MM/YYYY格式为Date对象
  const parseDate = (dateStr: string): Date => {
    const [day, month, year] = dateStr.split('/').map(Number);
    return new Date(year, month - 1, day);
  };

  const selected = parseDate(selectedDate);
  const compare = parseDate(arrayDate);

  // 计算日期差(取绝对值后判断是否为1天)
  const diffMs = Math.abs(selected.getTime() - compare.getTime());
  const diffDays = diffMs / (1000 * 60 * 60 * 24);

  return diffDays === 1;
};

2. 自定义表单验证器

基于Angular的Reactive Forms编写自定义验证器,传入已有日期数组作为参数:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export const forbiddenConsecutiveDateValidator = (dateArray: string[]): ValidatorFn => {
  return (control: AbstractControl): ValidationErrors | null => {
    const selectedDate = control.value;
    if (!selectedDate) return null; // 未选择日期时跳过验证

    // 检查数组中是否存在连续日期
    const hasConsecutive = dateArray.some(date => isConsecutiveDate(selectedDate, date));

    // 存在连续日期则返回错误对象,否则返回null
    return hasConsecutive ? { consecutiveDate: '所选日期与已有日期存在连续日期,无法提交' } : null;
  };
};

3. 组件中应用验证器

在组件的表单构建逻辑中,将自定义验证器绑定到日期控件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { forbiddenConsecutiveDateValidator } from './validators/date-validators';

@Component({
  selector: 'app-date-form',
  templateUrl: './date-form.component.html'
})
export class DateFormComponent implements OnInit {
  dateForm: FormGroup;
  existingDates = ['31/12/2021', '01/11/2021', '02/01/2022'];

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.dateForm = this.fb.group({
      selectedDate: [
        '',
        [
          Validators.required,
          forbiddenConsecutiveDateValidator(this.existingDates)
        ]
      ]
    });
  }

  // 便捷获取控件,用于模板错误提示
  get selectedDate() {
    return this.dateForm.get('selectedDate');
  }
}

4. 模板中显示错误提示

在HTML模板中绑定表单,并根据验证状态显示错误信息:

<form [formGroup]="dateForm">
  <label for="selectedDate">选择日期:</label>
  <input type="date" id="selectedDate" formControlName="selectedDate" />
  
  <!-- 连续日期错误提示 -->
  <div class="error-message" *ngIf="selectedDate.invalid && (selectedDate.dirty || selectedDate.touched)">
    <div *ngIf="selectedDate.errors?.consecutiveDate">
      {{ selectedDate.errors.consecutiveDate }}
    </div>
    <!-- 必填项错误提示 -->
    <div *ngIf="selectedDate.errors?.required">
      请选择日期
    </div>
  </div>

  <button type="submit" [disabled]="dateForm.invalid">提交</button>
</form>

内容的提问来源于stack exchange,提问作者Zulfikar Badurdeen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:18:32