角输入类型datetime-local验证

时间:2019-01-08 11:56:19

标签: javascript angular

在我选择日期时间的角度应用程序中,我使用输入类型=“ datetime-local”。

 <input id="field_bookingTime" type="datetime-local" class="form-control" name="bookingTime" [(ngModel)]="bookingTime"
   required/>

现在,我需要禁用当前日期之前的日期和当前日期之后3天的日期。例如,对于min,我添加了如下所示的验证。但是验证不起作用,仍然在显示的日历中启用了以前的日期。

currentDate = new Date();

     <input [min]="currentDate" id="field_bookingTime" type="datetime-local" class="form-control" name="bookingTime" [(ngModel)]="bookingTime"
       required/>

3 个答案:

答案 0 :(得分:0)

尝试用短划线设置日期格式:

示例:

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/>

或者只使用其他没有空格的日期格式...

答案 1 :(得分:0)

我建议为表单控件编写一个custom validator。最小值和最大值具有错误的browser support,但对于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]
    })
    ...

答案 2 :(得分:0)

类型<input>

datetime-local元素只接受yyyy-MM-ddThh:mm格式的min和max值作为字符串。由于new Date()返回的字符串格式不正确,因此min和max无效。只需将日期转换为正确的格式即可。

currentDate = new Date().toISOString().substring(0, 16);

在这里,我们首先将日期转换为期望的格式,方法是将其转换为简化的扩展ISO格式(ISO 8601),该格式始终为24或27个字符,然后在{之后删除字符{1}}

相关问题