1

I'm trying to create a regex for correct username validation in Ruby on Rails but for some reason I am doing something incorrect where all username inputs are invalid. I am allowing for upper-case characters, lower-case characters, numbers, and underscores.

Ruby on Rails name validation regex code:

validates :name, :format => {:with => /\A[A-Za-z\d_]\z/}

What am I doing wrong?

Thanks

1
  • Try using capital \Z or try with ^ and $ instead Commented Oct 23, 2011 at 22:53

2 Answers 2

3
validates :name, :format => {:with => /^[A-Za-z0-9\_]+$/}

Nice page to test regular expressions in ruby: http://rubular.com/

Sign up to request clarification or add additional context in comments.

2 Comments

I do not think that an empty string should validate. Do you?
except... for replacing the \A\z with ^$ see: guides.rubyonrails.org/security.html#regular-expressions
1
# \A[A-Za-z\d_]\z
# 
# Options: ^ and $ match at line breaks
# 
# Assert position at the beginning of the string «\A»
# Match a single character present in the list below «[A-Za-z\d_]»
#    A character in the range between “A” and “Z” «A-Z»
#    A character in the range between “a” and “z” «a-z»
#    A single digit 0..9 «\d»
#    The character “_” «_»
# Assert position at the very end of the string «\z»

This is your expression. Do you really want to match a single character?

I believe that :

/^\w+$/

this is what you are looking for. \w is a shorthand character class for what you have written. The above regex will match a string which consists only of A-Za-Z0-9_

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.