I’m trying to apply a format validation to a model, but when I create the model it isn’t coming back as invalid. I added a length validation and it works just fine. What am I doing wrong?
require 'rubygems'
require 'active_record'
class User < ActiveRecord::Base
validates :username, :format => { :with => /[A-Za-z]+/, :message => "Only letters a-z are allowed" }
validates :username, :length => { :maximum => 20, :too_long => "%{count} letters is too many"}
end
ActiveRecord::Base.establish_connection( ... )
user = User.create!(:username => 'johnsmith1234', :signupdate => '2010-11-12')
puts user.valid?
The output is always true unless I have a length of over 20 characters, then I get an error on the length. So why doesn’t the format validation fire?
/[A-Za-z]/checks for one or more alphabets in given string. If you want only alphabets you need to specify^and$. (i.e)/^[A-Za-Z]$/One more thing use
newto create new user. Becausecreateorcreate!will throw error if your validation fails.