0

我正在尝试对模型应用格式验证,但是当我创建模型时,它并没有返回为无效。我添加了一个长度验证,它工作得很好。我究竟做错了什么?

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 个字符,否则输出始终为真,然后我收到长度错误。那么为什么格式验证不会触发呢?

4

1 回答 1

2

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

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

还有一件事用于new创建新用户。因为createorcreate!会在你的验证失败时抛出错误。

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  
于 2013-02-05T18:36:18.267 回答