-1

Hello I wanted to do autofiller to match to this format "HH:MM". I wanted to check only against this regex /^(0[1-9]|1[012]):[0-5][0-9]$/ but have no idea how to match regex substring. I've looked at wikipedia and some sites and can't find modificator to check for 'subregex'. Doesn't this option exist? I've finally solved this problem with code below, but this array could certainly be generated programmatically, so there should already be solution I am searching for. Or it doesn't exist and I should write it?

patterns = [ /./, /^[0-9]$/, /^(0?[1-9]|1[012])$/, /^(0[1-9]|1[012]):$/, /^(0[1-9]|1[012]):[0-5]$/, /^(0[1-9]|1[012]):[0-5][0-9]$/]
unless patterns[newTime.length].test(newTime)

  newTime = newTime.substring(0, newTime.length - 1)
Machiaweliczny
  • 572
  • 1
  • 6
  • 16

1 Answers1

0

You could probably accomplish the same thing a bit more efficient.
Combine the regexes into a cascading optional form, then use the match length, substring
and a template to auto complete the time.

Pseudo code (don't know JS too well) and real regex.

 # pseudo-code:
 # -------------------------
 # input = ....;
 # template = '00:00';
 # rx = ^(?:0(?:[0-9](?::(?:[0-5](?:[0-9])?)?)?)?|1(?:[0-2](?::(?:[0-5](?:[0-9])?)?)?)?)$     
 # match = regex( input, rx ); 
 # input = input + substr( template, match.length(), -1 );


 ^    
 (?:
      0 
      (?:
           [0-9] 
           (?:
                : 
                (?:
                     [0-5] 
                     (?: [0-9] )?
                )?
           )?
      )?
   |  
      1 
      (?:
           [0-2] 
           (?:
                : 
                (?:
                     [0-5] 
                     (?: [0-9] )?
                )?
           )?
      )?
 )
 $