如何防止jQuery时间选择器中的无效时间值?

问题描述

我正在使用JQuery时间选择器,并试图防止用户插入无效字符(字母)。

知道我的系统中有4种时间格式,所以我不能使用RegExp或mask。

所以我想知道是否有办法做到这一点。

$('.gcureservationtimepicker').timepicker({
    timeFormat: '@AdminSiteHelper.GCUTimeFormat()',// timeFormat: 'HH:mm:ss',interval: 15,//maxTime: '12:00 PM',//defaultTime: '8',//startTime: '10:00',dynamic: false,dropdown: true,scrollbar: true,change: GenerateNewTimePicker
});

解决方法

根据我在Timepicker's Docs上看到的内容,它基本上会解释您在该字段中写的内容,因此,禁用字母的使用将限制其功能。

如果您希望将选项限制为仅接送时间,我建议您使用Pickadate as a time picker。用法类似,但该字段为只读。

更新

如果您不能更改库,而需要使用时间选择器,那么我将考虑限制输入的输入选项。类似于下面的示例。

另外,根据您的兼容性要求,另一种选择是使用<input type="time">,它已经具有许多您需要的限制。

附加说明

如果您愿意,还可以进一步研究下面添加的简单验证,并使用正则表达式或定位。像这样:

  1. 字符1和2只能是00到23或01到12之间的数字,具体取决于它是12h还是24h。
  2. 字符3只能是冒号。
  3. 第4个和第5个字符只能是数字。
  4. 输入字符串最多可以包含5个字符。

上述结构的正则表达式(未验证最小和最大数量)可以是:^\d{2}:\d{2}$

function checkNumber() {
  var e = event || window.event; // get event object
  var key = e.keyCode || e.which; // get key cross-browser

  var allowedKeys = [8,48,49,50,51,52,53,54,55,56,57,58,186]; // includes backspace,numbers and :

  if (!allowedKeys.includes(key)) {
    if (e.preventDefault) e.preventDefault(); //normal browsers
    e.returnValue = false; //IE
  }
}
<input type="text" id="onlytime" onkeydown="checkNumber()" placeholder="Input time">

<br><br>

<input type="time" id="justintime">