Skip to content

Commit

Permalink
feat: add Vx.valid?/2
Browse files Browse the repository at this point in the history
  • Loading branch information
tlux committed Mar 25, 2024
1 parent e80c8e7 commit 0dd1f7f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/vx.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ defmodule Vx do

@doc """
Validates a value against a given schema.
## Examples
iex> Vx.validate(Vx.String.t(), "foo")
:ok
iex> Vx.validate(Vx.String.t(), 123)
{:error, %Vx.Error{message: "must be a string", schema: Vx.String.t(), value: 123}}
"""
@spec validate(t, any) :: :ok | {:error, Error.t()}
def validate(schema, value) do
Expand All @@ -23,11 +31,36 @@ defmodule Vx do

@doc """
Validates a value against a given schema. Raises on error.
## Examples
iex> Vx.validate!(Vx.String.t(), "foo")
:ok
iex> Vx.validate!(Vx.String.t(), 123)
** (Vx.Error) must be a string
"""
@spec validate!(t, any) :: :ok | no_return
def validate!(schema, value) do
with {:error, error} <- validate(schema, value) do
raise error
end
end

@doc """
Checks if a value is valid against a given schema.
## Examples
iex> Vx.valid?(Vx.String.t(), "foo")
true
iex> Vx.valid?(Vx.String.t(), 123)
false
"""
@doc since: "0.4.0"
@spec valid?(t, any) :: boolean
def valid?(schema, value) do
validate(schema, value) == :ok
end
end
2 changes: 2 additions & 0 deletions test/vx_test.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
defmodule VxTest do
use ExUnit.Case, async: true

doctest Vx

@valid_values %{
"name" => "foo",
"age" => 18,
Expand Down

0 comments on commit 0dd1f7f

Please sign in to comment.