MPL
MPL

Reputation: 396

Rails field validation not working as expected

I have a users table with a row called screen_name which is a string.

Among other constraints the screen name should not contain characters like . , & % @ etc. To this end I constructed following validator:

validates :screen_name, presence: true,
          length: { maximum: 15 },
          uniqueness: { case_sensitive: false },
          format: { with: /\w+/ }

When I then enter a screen name like foo.bar it was happily accepted and stored in the database.

What am I doing wrong?

# == Schema Information
#
# Table name: users
#
#  id              :integer          not null, primary key
#  name            :string(255)
#  email           :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  password_digest :string(255)
#  remember_token  :string(255)
#  admin           :boolean          default(FALSE)
#  screen_name     :string(255)    
#

Upvotes: 0

Views: 196

Answers (1)

Raj Adroit
Raj Adroit

Reputation: 3878

change your validation like this /^\w*$/

or

You can validate like this

validates_format_of :screen_name, :with => /^[A-Za-z0-9.&]*\z/

Upvotes: 1

Related Questions