Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegExp for HH:MM time format in Flutter

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading