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

Don't allow consecutive same character and some different character together in TextFormField

I want to restrict the TextFormField to only accept numbers separated by commas and sometimes with dashes but I don’t want them to come consecutive to each other and also don’t want the same character consecutive.

Ex:-

  • 1,3-4,9-11 is correct
  • 1,,3--4,9-11 is wrong
  • 1,-3-4,9-11 is wrong
  • 1-,3-4,9-11 is wrong

To restrict things to only numbers, commas and dashes I’m using:-

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

FilteringTextInputFormatter(
   RegExp("[0-9,-]"),
   allow: true
)

But it is not restricting the consecutive behavior as shown in the wrong behavior in the examples.

So, how can I restrict my TextFormField to the correct behavior represented in the examples?

Thank you.

>Solution :

If you want to validate on submit, you might write the pattern as:

^[0-9]+(?:[,-][0-9]+)*$

Regex demo

If a negative lookahead is supported, you an exclude matching 2 times one of - or , while validating on typing.

Note that this will allow , or - at the end:

^(?!.*[,-][,-])[0-9,-]*

Regex demo

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