I've spend almost an hour reading similar posts but still no success on formating a single input field to mask input values in format (00:00).

我已经花了近一个小时阅读了类似的文章,但仍然没有成功地形成一个输入字段来屏蔽格式的输入值(00:00)。

So far here's the code but don't know why it doesn't work:

到目前为止,这是代码,但不知道为什么它不起作用:

    $('.houronly').keyup(function(){
        this.value=this.value.toString().replace(/^(([0-1][0-9]|2[0-3]|[0-9])|([0-1][0-9]|2[0-3]|[0-9])(:|h)[0-5]?[0-9]?)$/, "$1");
    });

4 个解决方案

#1


3

Take this as a toy answer if you like, but I made a method to mask the 24h time input as the user types it because in your question you have

如果你喜欢的话,可以把这个当作玩具一样的回答,但是我做了一个方法,在用户输入时屏蔽24小时的输入,因为在你的问题中你有

$('.houronly').keyup(function(){ .. }

so I presume you want masking while the user is typing.

所以我假设你想要屏蔽当用户输入的时候。

As the user types in 24h clock times, impossible key sequences should be truncated or rejected on the fly. I made a series of replacement rules that build on previous rules to accomplish this. When the input loses focus, a final check for 24h time validity is performed.

当用户在24小时内输入时,不可能的密钥序列应该被动态地截断或拒绝。为了实现这一点,我制定了一系列替代规则。当输入失去焦点时,将执行24h时间有效性的最后检查。

Now, in your original regex, you have (:|h) so I assume you want to allow times formatted like "23h".

现在,在原来的regex中,您有(:|h),所以我假设您希望允许格式化为“23h”的时间。

Code:

代码:

function replaceBadInputs(val) {
  // Replace impossible inputs as they appear
  val = val.replace(/[^\dh:]/, "");
  val = val.replace(/^[^0-2]/, "");
  val = val.replace(/^([2-9])[4-9]/, "$1");
  val = val.replace(/^\d[:h]/, "");
  val = val.replace(/^([01][0-9])[^:h]/, "$1");
  val = val.replace(/^(2[0-3])[^:h]/, "$1");      
  val = val.replace(/^(\d{2}[:h])[^0-5]/, "$1");
  val = val.replace(/^(\d{2}h)./, "$1");      
  val = val.replace(/^(\d{2}:[0-5])[^0-9]/, "$1");
  val = val.replace(/^(\d{2}:\d[0-9])./, "$1");
  return val;
}

// Apply input rules as the user types or pastes input
$('.houronly').keyup(function(){
  var val = this.value;
  var lastLength;
  do {
    // Loop over the input to apply rules repeately to pasted inputs
    lastLength = val.length;
    val = replaceBadInputs(val);
  } while(val.length > 0 && lastLength !== val.length);
  this.value = val;
});

// Check the final result when the input has lost focus
$('.houronly').blur(function(){
  var val = this.value;
  val = (/^(([01][0-9]|2[0-3])h)|(([01][0-9]|2[0-3]):[0-5][0-9])$/.test(val) ? val : "");
  this.value = val;
});

Demo

更多相关文章

  1. 如何以小时为单位从oracle数据库中获取数据
  2. 做自己的Android ROM,屏蔽对framework中的系统APK的签名检查
  3. 昨天花了两个小时做了一个天气预报的Demo,希望对新人有所帮助。
  4. Android下usb host接口插入usb设备时,如何屏蔽usb权限的提示框? 如
  5. Java中累计时间的计算(以小时为最终结果)
  6. (Java)出现/消失JPanel中的JLabel仅在调整大小时消失

随机推荐

  1. Django EventLog:传入当前用户
  2. Python---64位的windows系统中python的下
  3. 编程语言与Python学习(二)
  4. Python基础--图形用户界面GUI
  5. python tkinter窗口弹出置顶的方法
  6. Python 身份运算符
  7. Python基础之socket编程
  8. Fast RCNN的配置流程
  9. 在Python中的大文件中拆分行的内存问题
  10. Python之CMDB资产管理系统