javascript - 如何防止进入未来日期角度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";
}
我似乎无法在互联网上找到任何帮助。有人能帮我吗?谢谢
解决方案
由于您使用的是 ngbDatepicker,因此一种选择是设置maxDate
属性并添加readonly
属性。这样,用户将被迫使用日期选择器,并且不要直接在输入字段中输入任何其他内容。
[maxDate]="maxDate" readonly
推荐阅读
- ios - 如何让 Google 的 PlacePicker 在 iOS 上运行?
- regex - 如何使用 Bash 从 JSON 字符串中删除 \n 和 \r?
- android - 如何修复“不变对象作为反应子项无效”
- c++ - 尝试在数组中查找平均值时获取 -nan(ind) 输出(c++)
- java - ARCore中_ShowAndroidToastMessage()的作用是什么?
- r - 将列名称更改应用于数据框列表,但更改未反映在原始数据框中
- mysql - MySQL中的两个选择错误“每个派生表必须有自己的别名”?
- haskell - 如何在 Haskell 中编写模式准引用器?
- kotlin - Kotlin 类扩展
- angular - ionic 4 解析和提取 html 页面