Home > OS >  RegExp for HH:MM time format in Flutter
RegExp for HH:MM time format in Flutter

Time:03-20

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?

CodePudding user response:

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.
  • Related