views:

37

answers:

1

NOT a Rails 3 issue

In a Contact model I have a company_name attribute. For reasons that don't matter to this question, I want to prohibit an ampersand character. We have a lot of clients with ampersands in their company name, and users forget they aren't allowed to use this character.

This isn't an html sanitize issue. I don't care about whitespace or CDATA or anything. The entries in this field are plain text and I don't want an ampersand to be entered in this one field in any way, shape or form.

I assume a validation on the model is the way to go. I have tried validates_exclusion_of. I have tried validates_format_of. No success. I'm unsophisticated when it comes to regex, so I might be doing things very wrong. But the bottom line is - I need to prevent a user from entering that "&" character in the company_name field.

Thanks a million.

Steve

A: 
validates_format_of :company_name, :with => /\A[^&]*\Z/

But probably you could just remove ampersands before saving record:

before_save :strip_ampersands

def strip_ampersands
  company_name.gsub!("&", "")
end
Voyta
Voyta - thank you SO much. Actually the before_save option is perfect because I can use that to transparently swap the ampersand for the word "and." Perfect!