我有一个表单,我正在尝试验证名为“生日”的字段不为空,并且日期是 Chronic gem 可以解析的有效日期格式。我总是收到错误消息“生日无效”。我一直在尝试一种简单的格式“10/10/2010”。
我如何验证生日字段是慢性可以解析的格式?
User.rb 模型
class User < ActiveRecord::Base
validates :birthday, :presence => true
validate :birthday_is_date
validate :position, :presence => true
# validate the birthday format
def birthday_is_date
errors.add(:birthday ,Chronic.parse(birthday)) # testing to see the value of :birthday
errors.add(:birthday, "is invalid test message") if ((Chronic.parse(:birthday) rescue ArgumentError) == ArgumentError)
end
end
联系人控制器.rb
# POST /contacts/1/edit
# actually updates the users data
def update_user
@userProfile = User.find(params[:id])
respond_to do |format|
if @userProfile.update_attributes(params[:user])
format.html {
flash[:success] = "Information updated successfully"
redirect_to(profile_path)
}
else
format.html {
flash[:error] = resource.errors.full_messages
render :edit
}
end
end
end