javascript - 防止用户输入 future 日期 Angular 4

标签 javascript angular typescript date

我有一个 dateOfBirth 对象,我用 moment 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对象。您可以直接比较它们而无需解析它们,并使用带有自定义验证器的响应式(Reactive)表单,这还允许您在输入正确的日期之前使表单无效。

但是,如果你想保持当前的逻辑,你需要检查年份是否错误,然后检查年份是否正确但月份错误,然后检查年份和月份是否正确但日期错误。它最终会看起来非常难以辨认:

(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

关于javascript - 防止用户输入 future 日期 Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54803660/

相关文章:

javascript - 在 typescript 中将对象传递给 ._map

javascript - 箭头函数与类方法内存占用

css - Primeicons 不适用于树组件

javascript - 在 Javascript 中搜索关联数组/哈希

javascript - 使用功能更改文本并包含项目符号图像

javascript - JS脚本加载

javascript - "All but not"jQuery 选择器

javascript - "initialized"angular2-tree-component的事件在加载数据之前被调用

css - 如何在简单条件和三元条件下使用 [ngClass]?

Angular 2/4 在哪里存储 token