如何阻止用户在 angular 的日期类型输入中输入未来日期

我已限制用户将来使用 html 5 日期选择器在输入中输入日期。但用户可以输入未来的日期。如果用户不选择从日期选择器日历中选择日期值,有没有办法阻止用户输入未来的日期?


这是我的代码:


HTML


  <div class="col-sm-7">


    <input type="date" class="form-control" [max]="maxDate" pattern="^(19[5-9][0-9]|20[0-4][0-9]|2050)[-/](0?[1-9]|1[0-2])[-/](0?[1-9]|[12][0-9]|3[01])$" name="Datebillabuse" [(ngModel)]="Datebillabuse" #date="ngModel" [ngClass]="{ 'is-invalid': f.submitted && date.invalid }" required />

    <div *ngIf="f.submitted && date.invalid" class="invalid-feedback">

        <div *ngIf="date.errors.required">Date is required</div>

        <div *ngIf="date.errors.pattern">Please enter a valid date</div>

        <div *ngIf='date.errors.max'>Date must not be in future</div>

    </div>

  </div>

打字稿


  setTodayDate() {


    const dtToday = new Date();

    let month = String(dtToday.getMonth() + 1);

    let day = String(dtToday.getDate());

    let year = dtToday.getFullYear();



    if (parseInt(month, 10) < 10) {

        month = '0' + month.toString();

    }

    if (parseInt(day, 10) < 10) {

        day = '0' + day.toString();

    }


     this.maxDate = `${year}-${month}-${day}`;


  }

http://img2.mukewang.com/6171039500017b2907610254.jpg

http://img2.mukewang.com/6171039c0001294707740237.jpg

我想到的一种解决方案是检查日期值是否大于今天并显示错误。

有没有更好的方法可以在 Angular 中解决它?


喵喔喔
浏览 145回答 1
1回答

梵蒂冈之花

当我们通过设置最大属性来限制用户时,html 输入类型日期元素存在问题,因为这不允许用户从日历下拉列表中选择日期,但用户仍然可以使用键盘输入不需要的值。所以这就是 hack,我曾经处理过这个问题声明一个布尔值来检查日期是否无效。未来日期错误:布尔值;声明一个方法来检查输入日期是否有效。checkDateValidity(日期:字符串):布尔{&nbsp; &nbsp; const mxDate = new Date(this.maxDate);&nbsp; &nbsp; const inputDate = new Date(date);&nbsp; &nbsp; if (inputDate > mxDate) {&nbsp; &nbsp; &nbsp; return this.futureDateError = true;&nbsp; &nbsp; }&nbsp; &nbsp; return this.futureDateError = false;}将此方法与(change)事件绑定。当日期无效且不提交表单时显示错误。日期不能在未来如果 (this.checkDateValidity(this.Datebillabuse)) { return; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript