Packages

Minimal Elixir Input Validator

Current section

Files

Jump to
saturn lib validator.ex
Raw

lib/validator.ex

# Copyright 2024 Clivern. All rights reserved.
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file.
defmodule Saturn.Validator do
@moduledoc """
Saturn Validator
"""
@uuid_expr ~r/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i
@doc """
Validate if value is nullable
"""
def is_null?(""), do: true
def is_null?(nil), do: true
def is_null?(value) do
String.trim(to_string(value)) == ""
rescue
_ ->
false
end
@doc """
Validate if value is empty
"""
def is_empty?(""), do: true
def is_empty?(value) do
String.trim(to_string(value)) == ""
rescue
_ ->
false
end
@doc """
Validate if value equal an argument
"""
def equal(value, arg) when is_struct(arg, Date) do
Date.compare(value, arg) == :eq
rescue
_ ->
false
end
def equal(value, arg) when is_struct(arg, DateTime) do
DateTime.compare(value, arg) == :eq
rescue
_ ->
false
end
def equal(value, arg) when is_struct(arg, NaiveDateTime) do
NaiveDateTime.compare(value, arg) == :eq
rescue
_ ->
false
end
def equal(value, arg) do
value == arg
end
def ends_with?(value, str) do
String.ends_with?(to_string(value), to_string(str))
rescue
_ ->
false
end
def is_uuid?(value) do
Regex.match?(@uuid_expr, value)
rescue
_ ->
false
end
def between(value, min, max) do
value >= min and value <= max
end
def gt(value, arg) do
value > arg
end
def lt(value, arg) do
value < arg
end
def gte(value, arg) do
value >= arg
end
def lte(value, arg) do
value <= arg
end
end