How to validate full string with Regex

I currently developing a rest API with elixir and plug.

I will like to validate user input to accept only letters, but when I use the regex, it only validates a letter, not the full string.

Example:
String.match?(“A”, ~r/^[a-z]$/i) returns true, but when I try String.match?(“foo”, ~r/^[a-z]$/i) returns false.

Any help, please?

The regex asks for a single lowercase letter from the Latin alphabet. If you want to have at least one of those and do not care for an upper bound you need to use the + quantifier: ~r/^[a-z]+$/.

Thank Nobbz, but lets say I have a field for username, and I want the username to contain only letters and numbers, How do go about it

Letters and numbers is broad… I consider ä a letter, do you? What’s about Chinese scripts? Or kyrillic? Greek? Persian numbers? Do you consider those as valid?

If you restrict to Arabic numerals and Latin letters in upper and lowercase it’s something like this:

~r/^[a-zA-Z0-9]+$/
2 Likes

And there it was!!!. Thanks man, really appreciate

If you don’t mind underscores in there as well, you could use the \w “word characters” class, for example:

~r/^\w+$/

The \w class is equivalent to [A-Za-z0-9_].

1 Like

Thank you