Javascript 角度输入类型日期时间本地验证
在日期时间选择的角度应用程序中,我使用输入类型=“datetime local”Javascript 角度输入类型日期时间本地验证,javascript,angular,Javascript,Angular,在日期时间选择的角度应用程序中,我使用输入类型=“datetime local” 现在我需要禁用当前日期之前的日期和当前日期之后3天的日期。例如,对于min,我添加了如下所示的验证。但是验证不起作用,仍然会在显示的日历中启用以前的日期 currentDate = new Date(); <input [min]="currentDate" id="field_bookingTime" type="datetime-local" class="form-control" na
现在我需要禁用当前日期之前的日期和当前日期之后3天的日期。例如,对于min,我添加了如下所示的验证。但是验证不起作用,仍然会在显示的日历中启用以前的日期
currentDate = new Date();
<input [min]="currentDate" id="field_bookingTime" type="datetime-local" class="form-control" name="bookingTime" [(ngModel)]="bookingTime"
required/>
currentDate=新日期();
尝试使用破折号设置日期格式:
例如:
pipe = new DatePipe('en-US');
minDate = new Date();
minDateOut = pipe.transform(minDate, 'yyyy-MM-dd');
maxDate = new Date(minDate.getTime() + (1000 * 60 * 60 * 24 * 3));
maxDateOut = pipe.transform(maxDate, 'yyyy-MM-dd');
<input
[min]="minDateOut"
[max]="maxDateOut"
id="field_bookingTime"
type="datetime-local"
class="form-control"
name="bookingTime"
[(ngModel)]="bookingTime"
required/>
pipe=newdatepipe('en-US');
minDate=新日期();
minDateOut=pipe.transform(minDate,'yyyy-MM-dd');
maxDate=新日期(minDate.getTime()+(1000*60*60*24*3));
maxDateOut=pipe.transform(maxDate,'yyyyy-MM-dd');
或者只使用任何其他不带空格的日期格式…我建议为表单控件编写一个。Min和max有坏消息,这也适用于datetime local
function dateValidator(c: FormControl) {
// Not sure if c will come in as a date or if we have to convert is somehow
const today = new Date();
if(c.value > today) {
return null;
} else {
return {dateValidator: {valid: false}};
}
}
...
myForm = this.formBuilder.group({
date: ['', dateValidator]
})
...
类型为datetime local
的元素只接受yyyy-MM-ddThh:MM
格式的最小值和最大值作为字符串。由于new Date()
返回的字符串格式不正确,因此min和max将不起作用。只需将日期转换为如下所示的正确格式
currentDate = new Date().toISOString().substring(0, 16);
在这里,我们首先将日期转换为所需的格式,方法是将其转换为简化的扩展ISO格式(ISO 8601),其长度始终为24或27个字符,然后删除
yyyy-MM ddThh:MM
在任何情况下都要使用的输入吗?是,我使用的是angular模板驱动的表单我对我的项目有国际化支持,因此通过预定义“en-US”,可能会影响其他区域,您可以像这样获得区域设置:let locale=Intl.DateTimeFormat().resolvedOptions().locale;或者只需使用另一种方法格式化日期字符串,您不必使用DatePipe…或者使用Angular Material Team Alternative杠杆。这似乎不适用于显示区域设置时间tho。只有格林尼治时间?
currentDate = new Date().toISOString().substring(0, 16);