Rails model attribute allow nil but validate when not -
i want validate input box value in 2 cases:
- if nil? save successfully, no errors
- if not nil? validate format
i have simple line here:
validates :ip_addr, format: { with: regexp.union(resolv::ipv4::regex)} this work in cases won't allow nil/empty value throws exception. 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 if input invalid e.g. "33@@@#$" returns "true".
how include both cases ? possible ?
edit: seems regexp.union(resolv::ipv4::regex).match("something") returns nil if validation works same way, return nil in wrong values , allow_nil: true allow them persisted this.
try this
validates :ip_addr, format: { with: regexp.union(resolv::ipv4::regex)}, if: :ip_addr i not sure whether above 1 work. if doesn't, 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 want show") end end
Comments
Post a Comment