当前位置: 代码迷 >> JavaScript >> 防止用户输入将来的日期角度4
  详细解决方案

防止用户输入将来的日期角度4

热度:23   发布时间:2023-06-03 18:11:05.0

我有一个dateOfBirth对象,并且用js时刻创建了今天日期的对象,但是当我比较它们时,即使输入的日期小于今天的日期,它也会给我一个错误

这是我的html文件

<div class="form-group datepicker">
      <label for="dob">Date of Birth*</label>
      <div class="row input-group">
        <input
          ngbDatepicker
          #d="ngbDatepicker"
          #dobF="ngModel"
          class="form-control input-underline input-lg"
          id="dob"
          [(ngModel)]="dateOfBirth"
          placeholder="yyyy-mm-dd"
          name="dp"
          [ngClass]="{
            invalid:
              (dobF.value === null || isString(dobF.value) || (dateOfBirth.year > dobYear || dateOfBirth.month > dobMonth || dateOfBirth.day > dobDay) ) && dobF.touched
          }"
          required
        />
        <div class="input-group-append">
          <button
            class="btn btn-outline-secondary calendar"
            (click)="d.toggle()"
            type="button"
          ></button>
        </div>
      </div>
      <div
        *ngIf="
          (dobF.value === null || isString(dobF.value)  || dateOfBirth.year > dobYear || dateOfBirth.month > dobMonth || dateOfBirth.day > dobDay ) && dobF.touched
        "
        class="error"
      >
        Please enter a valid date of birth.
      </div>
    </div>

这是我的ts文件,其中定义了我的dob代码

 public dateOfBirth: { year: number; month: number; day: number };
 public currentDate = moment().format("YYYY-MM-DD");
 public dobYear: any;
 public dobMonth: any;
 public dobDay: any;

  let obj = this.currentDate.split("-");
let obj2 = obj.map(Number);
this.dobYear = obj2[0];
this.dobMonth = obj2[1];
this.dobDay = obj2[2];

它给了我一个错误,因为今天的月份是02,所以当我输入2012-09-09时它给了我一个错误,因为02 <09那么如何防止这个错误? 谁能帮我? 谢谢

当然,这里的解决方案是仅使用Date对象。 您可以直接比较它们而无需解析它们,并使用带有自定义验证程序的反应式表单,这也将使您使表单无效,直到输入正确的日期为止。

但是,如果要保持当前的逻辑,则需要检查年份是否错误,如果年份正确,但是月份错误,那么年份和月份正确,但是日期错误。 它将看起来非常难以辨认:

(dobF.value === null || isString(dobF.value)  || dateOfBirth.year > dobYear || (dateOfBirth.year == dobYear && dateOfBirth.month > dobMonth) || (dateOfBirth.year == dobYear && dateOfBirth.month == dobMonth && dateOfBirth.day > dobDay) ) && dobF.touched

使用[max]防止用户输入将来的日期。 无需自己构建此验证器。

参见: :

HTML:

<input
  ngbDatepicker **[max]="maxDate"** ... 

控制器:

public maxDate = new Date()

我的建议如下。

  1. 由于您使用的是日期选择器,因此请禁用输入字段(将其标记为只读)
  2. 设置[maxDate] =“ maxDate”(今天是您可以通过以下代码获取的当前日期)

      import * as moment from "moment"; **Declare:-** maxDate: {}; today = new Date(); constructor(){ this.maxDate = { year: parseInt(moment(this.today).format('YYYY')), month: parseInt(moment(this.today).format('MM')), day: parseInt(moment(this.today).format('DD')), } } 
  相关解决方案