Rails 3: Validate IP String

后端 未结 7 860
孤独总比滥情好
孤独总比滥情好 2020-12-13 18:41

In Rails 3, is there a built in method for seeing if a string is a valid IP address?

If not, what is the easiest way to validate?

相关标签:
7条回答
  • 2020-12-13 19:12

    You can also just call standard's library IPAddr.new that will parse subnets, IPV6 and other cool things: (IPAddr) and return nil if the format was wrong.

    Just do:

    valid = !(IPAddr.new('192.168.2.0/24') rescue nil).nil?  
    #=> true
    
    valid = !(IPAddr.new('192.168.2.256') rescue nil).nil?  
    #=> false
    
    0 讨论(0)
提交回复
热议问题