jquery 屏蔽编辑时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2259843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery masked edit for time
提问by Victor
Using meioMask Pluginis there any way to set up a mask so it will accept valid time in 24h or even better in 12h system?
使用meioMask Plugin有什么方法可以设置掩码,使其在 24 小时内接受有效时间,甚至在 12 小时系统中更好?
$("#txtTime").setMask('time');
This plugin has a pre-defined 24h 'time' mask but it's not quite correct, so you can enter invalid time values like "29:00". Is this mask is not suitable for this purpose and if not which one would be better?
这个插件有一个预定义的 24 小时“时间”掩码,但它不太正确,所以你可以输入无效的时间值,比如“29:00”。这个面膜是不是不适合这个目的,如果不适合哪个更好?
回答by Alex LE
Try this:
尝试这个:
$.mask.rules.H = /([0-1][0-9]|2[0-3])/; // 24 hours
$.mask.masks.time = 'H:59';
$("#txtTime").setMask('time');
Correction:
更正:
The rules need to be for one character only, so having that in mind, you can swap the mask when the input starts with '2' and validate the next char to be [0-3]:
规则只需要针对一个字符,因此请记住这一点,您可以在输入以 '2' 开头时交换掩码并验证下一个字符为 [0-3]:
$("#txtTime").setMask("29:59")
.keypress(function() {
var currentMask = $(this).data('mask').mask;
var newMask = $(this).val().match(/^2.*/) ? "23:59" : "29:59";
if (newMask != currentMask) {
$(this).setMask(newMask);
}
});
Note: In this case i'm using the keypress event, make sure to handle the paste event if needed.
注意:在这种情况下,我使用的是按键事件,如果需要,请确保处理粘贴事件。