Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

How to call parameters for 'format' and 'with' option in models?

I am trying to validate :profile_name.

validates :profile_name, presence: { message: I18n.t('errors.messages.blank') }, format: { with: @profile_name.gsub(" ", ""), message: 'Must be formatted correctly.' }

I want to sanitize HTML, special characters, and all whitespaces for the profile name input. I let users use all kinds of languages for that.

My approach is to use 'sanitize' gem for HTML sanitizing and gsub method for the other things.

I just have no idea how to call profile_name parameter.

1 Answer

Yoochan,

The with method expects a Regular Expressions pattern to match against. If you are looking to do a little bit of formatting to the profile_name field before validations occur (so that you can remove whitespace elegantly, versus erring out), you can perform a before_validation callback.

before_validation :remove_whitespace

def remove_whitespace
  self.profile_name = profile_name.gsub(' ', '')
end

Now, if all goes well, this method will be called before any validations occur. Thus you can modify the parameters before they're judged.

As far as your validation is concerned. I would suggest you go back to using a RegEx pattern. One like the following:

validates :profile_name,  presence: { message: I18n.t('errors.messages.blank') }, 
                          format: { with: /^[a-zA-Z0-9]+$/, message: 'must be formatted correctly.' }

That pattern is saying: "only allow letters and numbers, of any case, and nothing else." The carot (^) tells RegEx that this is the beginning. And the dollar sign ($) tells RegEx that the end has been reached. The plus sign (+) requires RegEx match the preceding pattern at least one time in order to be successful.

Thank you so much, Bob Hensley! I successfully did what I wanted.

The below is what I did.

 before_validation :remove_whitespace
validates :profile_name, presence: { message: I18n.t('errors.messages.blank') }, format: { with: /./, message: 'Must be formatted correctly.' }
validates :profile_name, uniqueness: { message: I18n.t('validation.uniqueness.profile_name') }
 def remove_whitespace
 self.profile_name = Sanitize.clean(profile_name.gsub(' ', ''))
 end