defmodule Fields.Validate do @moduledoc """ Helper functions to validate the data in certain fields """ @doc """ Validate an address. Currently just validates that some input has been given. """ def address(address) do String.length(address) > 0 end @doc """ Validate the format of an email address using a regex. Uses a slightly modified version of the w3c HTML5 spec email regex (https://www.w3.org/TR/html5/forms.html#valid-e-mail-address), with additions to account for not allowing emails to start or end with '.', and a check that there are no consecutive '.'s. """ def email(email) do {:ok, regex} = Regex.compile( "^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]*(?\/\/=]*)$/ Regex.match?(regex, url) end def ip_address(ip_address) do # https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses {:ok, regex_ipv6} = Regex.compile( "(([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]))" ) # https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp {:ok, regex_ipv4} = Regex.compile("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}") Regex.match?(regex_ipv6, ip_address) || Regex.match?(regex_ipv4, ip_address) end end