Rails 3 validate IPv4 and IPv6 format
Asked Answered
O

2

6

I know the validation format for IPv4 and IPv6. But not sure how I can combine them so atleast one format should be true. Here is my validation

validates :src_ip_addr, :presence => true, :uniqueness => true,
            :format => { :with => Resolv::IPv4::Regex, :message => "Not an valid IPv4 format"}

  validates :src_ip_addr, :presence => true, :uniqueness => true,
            :format => { :with => Resolv::IPv6::Regex, :message => "Not an valid IPv6 format"}

How I can combine them so if one format is correct then validation should work. Should fail only if ipv4 and ipv6 format is not correct.

Thanks.

Observable answered 6/6, 2013 at 15:8 Comment(0)
J
15

You can also combine them with Regexp.union:

:format => { :with => Regexp.union(Resolv::IPv4::Regex, Resolv::IPv6::Regex) ...
Jetton answered 6/6, 2013 at 15:36 Comment(0)
C
0

You can do:

:format => { :with => Resolv::AddressRegex ...

...to match both IPv4 and IPv6.

Cutthroat answered 15/11, 2023 at 13:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.