开发者

Prohibit ampersand in Rails form

开发者 https://www.devze.com 2022-12-29 05:27 出处:网络
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 characte开发者_JS百科r. We have a lot of clien

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 characte开发者_JS百科r. 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消