Reputation: 11
I'm stuck trying to figure out how to make this method work.
I want to return true if the username is made up of lowercase characters, numbers, and underscores, and is between 4 and 16 characters in length, otherwise return false.
def validate_usr(username)
if username == /A[a-z0-9_]{4,16}Z/
return true
else return false
end
end
I don't know what I'm doing wrong.
Upvotes: 0
Views: 5743
Reputation: 160551
I'd use something like:
def validate_usr(username)
!!username[/\A\w{4,16}\z/]
end
validate_usr('foo') # => false
validate_usr('foobar') # => true
validate_usr('FooBar') # => true
validate_usr('Foo Bar') # => false
validate_usr('12345678901234567') # => false
\w
is the set [a-zA-Z0-9_]
, which includes uppercase too. If you don't want upper-case then use [a-z0-9_]
for the set.
[/\A\w{4,16}\z/]
is a String shortcut for applying a pattern to the string and returning the match. As the tests ran username[/\A\w{4,16}\z/]
returned:
username[/\A\w{4,16}\z/] # => nil, "foobar", "FooBar", nil, nil
!!
converts "truthy"/"falsey" to true
/false
, so here are the actual results:
!!username[/\A\w{4,16}\z/] # => false, true, true, false, false
The end result is the method returns the desired true/false results only with less code.
I used \z
rather than \Z
because you're testing usernames, presumably for correctness prior to creating an account. \z
applies the test to the entire string, whereas \Z
will ignore a trailing line-end. If your code were to somehow allow a user to create a name with a trailing line-end \Z
would not give you an accurate validation result:
"foobar\n"[/\A\w{4,16}\Z/] # => "foobar"
"foobar\n"[/\A\w{4,16}\z/] # => nil
Upvotes: 5
Reputation: 2588
How about this?
def validate_usr(username)
username =~ /\A[a-z0-9_]{4,16}\z/
end
Please read the following articles for the details of using regex.
=~
http://ruby-doc.org/core-2.1.1/Regexp.html\A
, \z
, \Z
Difference between \A \z and ^ $ in Ruby regular expressions and http://ruby-doc.org/core-2.1.1/Regexp.html#class-Regexp-label-AnchorsUpvotes: 2
Reputation: 80065
No regex:
def validate_usr(username)
username.size.between?(4, 16) && username.count("^a-z0-9_").zero?
end
Upvotes: 0
Reputation: 543
I think you're pretty close you'll want to use =~
for the regex comparison. It will return 0 if it is valid.
The match operator =~ can be used to match a string against a regular expression. If the pattern is found in the string, =~ returns its starting position; otherwise, it returns nil
def validate_usr(username)
(username =~ /\A[a-z0-9_]{4,16}\Z/) == 0
end
Upvotes: 0