我试图将格式验证应用于模型,但当我创建模型时,它不会返回为无效。我添加了一个长度验证,它运行得很好。我做错了什么?
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个字符,否则我会在长度上出错。那么,为什么格式验证没有启动呢?
/[A-Za-z]/
检查给定字符串中的一个或多个字母。如果只需要字母,则需要指定^
和$
。(即)/^[A-Za-Z]$/
validates :username, :format => { :with => /^[A-Za-z]+$/, :message => "Only letters a-z are allowed" }
还有一件事是使用new
来创建新用户。因为如果验证失败,create
或create!
将抛出错误。
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