Rails 3: Validate IP String

后端 未结 7 874
孤独总比滥情好
孤独总比滥情好 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:11

    The Rails way to validate with ActiveRecord in Rails 3 is:

    @ip_regex = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/
    
    validates :gateway, 
              :presence => true, 
              :uniqueness => true,
              :format => { :with => @ip_regex } 
    

    Good resource here: Wayback Archive - Email validation in Ruby On Rails 3 or Active model without regexp

提交回复
热议问题