views:

22

answers:

2

Hey guys, I thought this would be fairly straightforward, but it's not it seems..maybe I'm just writing the syntax wrong..

In my model I'm checking for certain key words

before_validation :deal_validation

def deal_validation
  if self.description.match /(exp\s|expire|ex\s|print|mention|\/)/ 
    errors.add(:description, "Now just a second! You can't use those words!")
  end    
end

But it doesn't seem to stop the saving of the model.

Am I missing something?

A: 

I don't really know ruby, but used rubular to test, and it seems like you want:

(\bexpire\b|\bexp?\b|\bprint\b|\bmention\b|\b\/\b)

the \b characters match word boundaries. as written, your regex will match anything with "/", as well as strings like "regex ". is that really what you want?

edited to improve it slightly using the "?" quantifier, which matches both "exp" and "ex"

Paul Sanwald
Careful: Putting `\b` around a non-word character (slash) means that it will only match when the slash is directly surrounded by word characters, i. e. the slash will be matched in `a/b` but not in `a / b` nor in `/`.
Tim Pietzcker
Thanks but my regex works all the same. Theres something not working with the errors being called or the validation never being performed.
Trip
thanks tim, I didn't know that!
Paul Sanwald
+1  A: 

Changed it to

validate :deal_validation

Works!

Trip
Yes - you are just telling it to run the function BEFORE validation. It's not actually affecting the validation.
jasonpgignac