非法日期 argument out of range错误
现象:
画面上有个text框,对应的字段在数据库里是datetime类型的(数据库是postgresql),对该text框也进行了validation验证。
但是输入非法日期2015/02/31,validation能正常check出来,只要是日期超过31号,就会报错argument out of range。
①view:
<%= f.text_field :uketori_date, class: "datepicker", maxlength: "10", style: "ime-mode:disabled;width:100px;" %>
②controller:
def create
@keiyakusho = Keiyakusho.new(keiyakusho_params) #<------- 就是这句话报错
respond_to do |format|
if @keiyakusho.save
format.html { redirect_to mainmenus_path, notice: I18n.t('msg.ICMN002', arg: I18n.t('models.keiyakusho')) }
else
format.html { render :new }
end
end
end
def keiyakusho_params
params.require(:keiyakusho).permit(:uketori_date, ……)
end
③model:
validates :uketori_date_before_type_cast, :date_format => { :attr_base => :uketori_date},
:allow_blank => true
④validation:
date_format_validator.rb:
class DateFormatValidator < ActiveModel::EachValidator
def validate_each(record, attr, value)
check_val = value.to_s.gsub(/-/,"/")
unless /^(\d{4})\/(\d{1,2})\/(\d{1,2})$/ =~ check_val
record.errors.add(options[:attr_base],"#{I18n.t('msg.ECMN010', arg: "")}")
return
end
split_date = check_val.split('/');
if Date.valid_date?(split_date[0].to_i,split_date[1].to_i,split_date[2].to_i) == false
record.errors.add(options[:attr_base],"#{I18n.t('msg.ECMN010', arg: "")}")
end
end
end