1

I'm using the RegEx from here

TextFormField(
  keyboardType: TextInputType.datetime,
  inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r'^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$')),
  ],
)

This RegExp doesn't let me enter anything. Then what should be the correct RegExp for time in HH:MM format for TextFormField?

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

2

In the FilteringTextInputFormatter.allow regex, you need to make sure that the pattern can match a single char input.

So, here, you need to use

^(?:[01]?\d|2[0-3])(?::(?:[0-5]\d?)?)?$

See the regex demo. Details:

  • ^ - start of string
  • (?:[01]?\d|2[0-3]) - an optional 0 or 1 and then any one digit, or 2 and then a digit from 0 to 3
  • (?::(?:[0-5]\d?)?)? - an optional non-capturing group matching one or zero occurrences of
    • : - a colon
    • (?:[0-5]\d?)? - an optional sequence of a digit from 0 to 5 and then an optional digit
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • A similar question is posted [here](https://stackoverflow.com/q/71538220/12483095). Would love to see your answer, thanks :) – iDecode Mar 19 '22 at 12:41
  • @iDecode I do not think that one is specifically unique. Just make sure your pattern matches a single char input. `r'^(?:[+0]9?)?[0-9]{0,12}$'` – Wiktor Stribiżew Mar 19 '22 at 12:44