简体   繁体   English

Javascript正则表达式可验证12小时

[英]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: 您可以从中得到什么:

  • If group 5 length == 2 (am/pm) the entire time is finished. 如果第5组的长度== 2(am / pm),则整个时间结束。
  • Group 1 contains the partial or full valid data. 组1包含部分或全部有效数据。
  • Group 2 contains the hours. 第2组包含小时。
  • Group 3 and 4 contain the minute digits (join together). 组3和4包含分钟数字(连接在一起)。
  • Group 5 contains the am/pm. 第5组包含上午/下午。

There are 2 ways to use this regex. 有两种使用此正则表达式的方法。

  1. As a test for validity. 作为有效性测试。 If it does not match, put a red box around the 如果不匹配,请在
    edit box and let the user figure out the mistake. 编辑框,让用户找出错误。
  2. As a self correcting match: 作为自校正匹配:
    • Take off the last $ in the regex, allowing a partial match. 删除正则表达式中的最后一个$ ,允许部分匹配。
    • After every match, write back the group 1 (partial) to the edit box 每次比赛后,将组1(部分)写回到编辑框中
      thus not allowing invalid entries. 因此,不允许输入无效的内容。
      Wait for a submit button, then validate the entire string (start to finish). 等待一个提交按钮,然后验证整个字符串(从头到尾)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM