首页 > 解决方案 > 如何防止进入未来日期角度4

问题描述

我想添加内联验证以防止用户输入未来的日期,例如如果我添加 2022 我应该给我一个错误,例如您添加错误的日期或其他内容

这是我的 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)) && 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)) && dobF.touched
        "
        class="error"
      >
        Please enter a valid date of birth.
      </div>
    </div>

这是我的 Ts 文件

我在哪里定义 dateOfBirth

public dateOfBirth: { year: number; month: number; day: number };
 constructor(
public router: Router,
public route: ActivatedRoute,
private modalService: NgbModal,
private store: Store<any>,
private authService: AuthService,
public config: NgbDatepickerConfig,
private duplicateFinderService: DuplicateFinderService
) 
{
const currentDate = new Date();
const day = currentDate.getDate();
const month = currentDate.getMonth() + 1;
const year = currentDate.getFullYear();
// customize default values of datepickers used by this component tree
this.config.minDate = { year: 1900, month: 1, day: 1 };
this.config.maxDate = { year, month, day };
// days that don't belong to current month are not visible
this.config.outsideDays = "hidden";
}

我似乎无法在互联网上找到任何帮助。有人能帮我吗?谢谢

标签: javascriptangulartypescriptwebmean

解决方案


由于您使用的是 ngbDatepicker,因此一种选择是设置maxDate属性并添加readonly属性。这样,用户将被迫使用日期选择器,并且不要直接在输入字段中输入任何其他内容。

[maxDate]="maxDate" readonly


推荐阅读