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

How to avoid multiple spaces in textfields?

Is there a way to stop the use of more than 1 space in a row in a textfield?.

Currently im using this code to deal with a single space, but the issue is that i dont want to end up with an infinitely long list of exceptions like the second image.

I gotta mention that i do want to use spaces, just not at the start of my text or multiples in a row.

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

Thank you in advance.

>Solution :

You could use trimRight() to strip all leading whitespace from your value.

If you want to deal with trailing whitespace as well, you could just use trim()

Either way, both of these would catch all the exceptions you listed, whether there is an empty value, or a value with only whitespace.

I’m unsure if you are asking how to also replace multiple spaces inside the string with just single space? To do that you can use a regex, like this:

    value = value.trim();
    var singleSpaces = value.replaceAll(RegExp(r"\s+"), " ");
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