ActiveRecord格式验证未触发

时间:2013-02-05 18:29:22

标签: ruby ruby-on-rails-3 activerecord

我正在尝试将格式验证应用于模型,但是当我创建模型时,它不会返回为无效。我添加了长度验证,它工作得很好。我做错了什么?

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?

除非我的长度超过20个字符,否则输出始终为true,然后我得到一个长度错误。那么为什么格式验证不会解决?

1 个答案:

答案 0 :(得分:2)

/[A-Za-z]/检查给定字符串中的一个或多个字母。如果您只想要字母,则需要指定^$。 (即)/^[A-Za-Z]$/

validates :username, :format => { :with => /^[A-Za-z]+$/, :message => "Only letters a-z are allowed" }

使用new创建新用户还有一件事。如果验证失败,createcreate!会抛出错误。

user = User.new(:name => "john123")
if user.valid?
  #do something
else
  #do something          `user.errors.full_messages` will have your validation messages if it has error
end