Page MenuHomeGRNET

No OneTemporary

File Metadata

Created
Sun, May 18, 11:58 PM
diff --git a/app/models/a.rb b/app/models/a.rb
new file mode 100644
index 0000000..2ccf7e4
--- /dev/null
+++ b/app/models/a.rb
@@ -0,0 +1,4 @@
+class A < Record
+ validates :content, presence: true, ipv4: true
+ validates :name, presence: true
+end
diff --git a/lib/ipv4_validator.rb b/lib/ipv4_validator.rb
new file mode 100644
index 0000000..55b4165
--- /dev/null
+++ b/lib/ipv4_validator.rb
@@ -0,0 +1,17 @@
+require 'ipaddr'
+require 'socket'
+
+class Ipv4Validator < ActiveModel::EachValidator
+ def valid_v4?(addr)
+ return false if addr['/'] # IPAddr accepts addr/mask format
+ IPAddr.new(addr, Socket::AF_INET)
+ true
+ rescue IPAddr::AddressFamilyError, IPAddr::InvalidAddressError
+ false
+ end
+
+ def validate_each(record, attribute, value)
+ return if valid_v4?(value)
+ record.errors[attribute] << 'is not a valid IPv4 address'
+ end
+end

Event Timeline