[英]Javascript regex for validating 12 hour time
I'm trying to build a 12 hour input component in Javascript and I want to validate the format in real time, as the user types, like a parser validates incoming tokens. 我正在尝试用Javascript构建一个12小时的输入组件,并且想实时验证格式,因为用户类型就像解析器一样会验证传入的令牌。
I'm using react, so in each render the field value gets passed trhough the following regex: 我正在使用react,因此在每个渲染中,字段值都通过以下正则表达式传递:
const validTime = /(0[1-9])|(1[0-2]):([0-5][0-9])\s((a|p|A|P)(m|M))/;
I test if the value is valid, if not I add a red border to the input, but with this approach I can write anything, it wouldn't get submitted but you could write something like ajsjjsdf , and I'm looking for something different. 我测试该值是否有效,如果不是,我会在输入中添加一个红色边框,但是使用这种方法我可以编写任何内容,不会提交任何内容,但是您可以编写类似ajsjjsdf的内容 ,而我正在寻找其他内容。 Allow the user to type only the characters allowed by the regex rule above in real time.
允许用户仅实时键入上述正则表达式规则允许的字符。
Edit: 编辑:
I'm adding some code... 我正在添加一些代码...
Basically the input simpliefied is: 基本上,简化的输入为:
<input
ref={(input) => {this[keyName] = input}}
className="form-control"
placeholder="09:00 AM"
value={scheduleTime ? scheduleTime.value : ''}
onChange={(ev) => this.onChangeTimeSchedule(ev, keyName)}/>
And the value handler: 和值处理程序:
onChangeTimeSchedule = (ev, scheduleKey) => {
const validChar = /[0-9]|[aApPmM]|[\s\b]|:/;
const validTime = /(0[1-9])|(1[0-2]):([0-5][0-9])\s((a|p|A|P)(m|M))/;
const { value } = ev.target;
if(!validTime.test(value))
return;
const { schedule } = this.state;
schedule[scheduleKey] = {value, invalid: false};
this.setState({schedule});
};
if I use validChar it would only allow the characters I want, but it would allow strings like 10:aaaM. 如果我使用validChar,它将只允许我想要的字符,但是将允许像10:aaaM这样的字符串。
If I use validTime (this is the check I do for each render, to add a red border if invalid) in this context, I always returns false, because it excepts a full match: 10:0 is wrong, 10:00 PM is correct. 如果在这种情况下使用validTime(这是我对每个渲染所做的检查,如果无效则添加红色边框),我将始终返回false,因为它完全匹配:10:0错误,10:00 PM正确。
This is one way to do it. 这是做到这一点的一种方法。 Set it to case insensitive.
将其设置为不区分大小写。
^(0(?:[1-9]|$)|1(?:[0-2]|$))(?:(:)(?:([0-5])(?:([0-9])(?:(\\s)([ap]m?)?)?)?)?)?$
What you can get with this: 您可以从中得到什么:
There are 2 ways to use this regex. 有两种使用此正则表达式的方法。
$
in the regex, allowing a partial match. $
,允许部分匹配。 Formatted / explained : 格式化 /解释:
^ # BOS
( # (1 start)
# Hours
( # (2 start)
0
(?: [1-9] | $ )
| 1
(?: [0-2] | $ )
) # (2 end)
# Minutes
(?:
: # ':'
(?:
( [0-5] ) # (3), Min,digit 1
(?:
( [0-9] ) # (4), Min,digit 2
(?:
\s # space
( # (5 start), AM / PM
[ap] m?
)? # (5 end)
)?
)?
)?
)?
) # (1 end)
$ # EOS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.