Last active
June 12, 2019 08:21
-
-
Save kzaitsev/9294c8318d5018d7e9b11cab61962d16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'resolv' | |
require 'dry/types' | |
require 'dry/validation' | |
require 'pp' | |
module MyTypes | |
include Dry.Types() | |
REGEX256 = Resolv::IPv4::Regex256 | |
REGEXP = { | |
ipv4_cidr: /\A(#{REGEX256})\.(#{REGEX256})\.(#{REGEX256})\.(#{REGEX256})\/(\d{1,2}?)\z/, | |
ipv6_cidr: /\A(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(\/((1(1[0-9]|2[0-8]))|([0-9][0-9])|([0-9])))?\z/ | |
} | |
Ipv4Cidr = Strict::String.constrained(format: REGEXP.fetch(:ipv4_cidr)) | |
Ipv6Cidr = Strict::String.constrained(format: REGEXP.fetch(:ipv6_cidr)) | |
Cidr = Ipv4Cidr | Ipv6Cidr | |
end | |
class ServerValidation < Dry::Validation::Contract | |
params do | |
optional(:network).value(MyTypes::Cidr) | |
optional(:networks).each(MyTypes::Cidr) | |
end | |
end | |
pp ServerValidation.new.call(network: 'not_cidr', networks: ['10.0.0.0/8', 'not_cidr']).errors | |
#<Dry::Validation::MessageSet messages=[] options={:locale=>:en}> | |
MyTypes::Cidr['not_cidr'] | |
# Dry::Types::ConstraintError: "not_cidr" violates constraints... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment