1

I have a check of the following type

 validates :callback_handle, :format => { :with => /[_0-9a-zA-Z]+/ix }, :unless  => "callback.nil?"

I do not want any non 0-9, a-z A-Z characters to pass. So i set callback_handle to "!alksjda" (note ! at the begining). This test does not fail. What am I doing wrong?

I tried a few things on irb: This is what I got:

1.9.2-p320 :001 > a = "!askldjlad"
 => "!askldjlad" 
1.9.2-p320 :002 > a =~ /[_0-9a-zA-Z]+/ix
 => 1 
1.9.2-p320 :003 > a = "askldjlad"
 => "askldjlad" 
1.9.2-p320 :004 > a =~ /[_0-9a-zA-Z]+/ix
 => 0 

I thought it would return false or nil on failure to find the match.

Can someone tell me what is wrong here in my understanding?

EDIT: I figured out that =~ will return position of a match. So the question becomes How do I not allow something that has any other character to not match?

0

2 Answers 2

3

Your regular expression is still able to match, because there is at least 1 character in your string that is alpha-numeric. If you want to make sure that the entire string matches then you should define the beginning and end of the match.

Old:

a =~ /[_0-9a-zA-Z]+/ix

This is saying "match at least one of these characters somewhere in a.

New:

a =~ /\A[_0-9a-zA-Z]+\z/ix

This is saying "start at the beginning of the string, then match at least 1 of only these characters, followed by the end of the string" in a.

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

3 Comments

Nope, this is saying about a line, not a string. "a\n!" =~ /^[_0-9a-zA-Z]+$/ix returns 0. You need to use \A+\z pair instead: /\A[_0-9a-zA-Z]+\z/ix.
Whats with the x-modifier?
The x is doing nothing in this particular case. It was copied from the original question, and I didn't worry about it, because it's also not hurting anything.
1

Your regex just asks that your string contains 1 or more valid characters ... this should fix it :

 validates :callback_handle, :format => { :with => /^[_0-9a-zA-Z]+$/ix }, :unless  => "callback.nil?"

1 Comment

Check this comment.

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.