我无法使用输入掩码插件,并尝试使用am | pm的子午线创建hh:mm的时间输入掩码。例如,输入不应允许用户以alpha开头...但是,如果模式不完全匹配,则我创建的模式(我想可以简化)将清除整个值。此掩码应在每次击键(或在这种情况下为输入)时均有效,因此应允许以下操作:
0
02
02:
02:3
02:35
02:35一个
上午02:35
$('.time').on('input', function (e) {
var input = $(this);
var value = input.val();
var pattern = /^(?!(^\d$)|(^\d\d$)|(^\d\d:$)|(^\d\d:\d$)|(^\d\d:\d\d$)|(^\d\d:\d\d\s$)|(^\d\d:\d\d\s(a|p)$)|(^\d\d:\d\d\s(am|pm)$)$).*/g;
var newvalue = value.replace(pattern, '');
input.val(newvalue);
});
答案 0 :(得分:0)
我最终使用:
$(selector).on('keypress', function (e) {
var input = $(this);
var value = input.val();
var length = value.length + 1;
var key = e.originalEvent.key;
value += key;
try {
var pattern = '';
if (length == 1 && value > 1) {
e.preventDefault();
return;
};
if (length == 1) pattern = /\d/gi;
else if (length == 2) pattern = /\d{2}/gi;
else if (length == 3) pattern = /\d{2}:/gi;
else if (length == 4) pattern = /\d{2}:\d/gi;
else if (length == 5) pattern = /\d{2}:\d{2}/gi;
else if (length == 6) pattern = /\d{2}:\d{2}\s/gi;
else if (length == 7) pattern = /\d{2}:\d{2}\s(a|p)/gi;
else if (length == 8) pattern = /\d{2}:\d{2}\s(a|p)m/gi;
if (pattern == '') {
e.preventDefault();
return;
};
var ok = pattern.test(value);
if (!ok) e.preventDefault();
} catch (e) {
HandleErrorMessages(e);
};
});
尽管它没有我想要的动态。
答案 1 :(得分:0)
尝试使用正则表达式:^\d(?:\d(?::(?:\d(?:\d(?:\s(?:(?:a|p)(?:m)?)?)??)?)?)?)?$