简体   繁体   English

Rails模型属性允许为nil,但不允许时进行验证

[英]Rails model attribute allow nil but validate when not

I want to validate an input box value in two cases: 我想在两种情况下验证输入框的值:

  1. If nil? 如果没有? then save successfully, no errors 然后保存成功,没有错误
  2. If not nil? 如果不是零? then validate its format 然后验证其格式

I have a simple line here: 我在这里有一条简单的线:

validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}

This will work in all cases but won't allow a nil/empty value as it throws an exception. 这将在所有情况下都有效,但由于抛出异常,因此将不允许使用nil / empty值。 But: 但:

validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}, allow_nil: true

and

validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}, allow_blank: true

Will allow nil/empty values but If the input is invalid eg "33@@@#$" then it returns "true". 将允许nil / empty值,但如果输入无效,例如“ 33 @@@#$”,则返回“ true”。

How could I include both cases ? 我怎样才能包括这两种情况? Is that possible ? 那可能吗 ?

EDIT: It seems that Regexp.union(Resolv::IPv4::Regex).match("something") returns nil so If the validation works the same way, it will return nil in wrong values and allow_nil: true will allow them to be persisted like this. 编辑:似乎Regexp.union(Resolv::IPv4::Regex).match("something")返回nil,因此,如果验证以相同的方式工作,它将以错误的值返回nil, allow_nil: true将允许它们这样坚持下去。

Try this 尝试这个

validates :ip_addr, format: { with: Regexp.union(Resolv::IPv4::Regex)}, if: :ip_addr

I am not sure whether the above one will work. 我不确定上述方法是否会起作用。 If it doesn't, do this 如果不是,请执行此操作

validate :ip_addr_format_check, if: :ip_addr

def ip_addr_format_check
  unless ip_addr =~ Regexp.union(Resolv::IPv4::Regex)
    errors.add(:base, "Error you want to show")
  end
end

Typecasting seems to be the problem. 类型转换似乎是问题所在。

The solution below works fine: 下面的解决方案工作正常:

validates :ip_addr, format: { with: Resolv::IPv4::Regex }, 
    presence: false, unless: Proc.new { |ifc| ifc.ip_addr_before_type_cast.blank? }

Most probably we need to check If the variable's value is blank before casting it to inet (postgreSQL). 最有可能我们需要在将变量强制转换为inet之前检查变量的值是否为空(postgreSQL)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM