lib/validators/format.ex

defmodule Dsv.Format do
  use Dsv.Validator

  @moduledoc """
  Check if the given `String` matches the regular expression.
  Dsv.Format module provides a functions to determine if a string matches a regular expression.

  """

  message("Value <%= data %> does not match pattern <%= Regex.source(options) %>")

  @doc """
  The `valid?/2` function evaluates whether a given string matches a specified regular expression.

  ## Parameters

    * `data` - The string to be checked against the regular expression.
    * `format` - The regular expression pattern to be used for matching.

  ## Returns

  A boolean value:

  - `true` if the `string` matches the `regex`.
  - `false` if the `string` does not match the `regex`.

  ## Examples

      iex> Dsv.Format.valid?("string to match", ~r/.*\ .*\ .*/)
      :true

      iex> Dsv.Format.valid?("stringtomatch", ~r/.*\ .*\ .*/)
      :false
  """
  def valid?(data, options: format), do: valid?(data, format)
  def valid?(data, format), do: String.match?(data, format)

  @doc """
  The `validate/2` function evaluates whether a given string matches a specified regular expression.

  ## Parameters

    * `data` - The string to be checked against the regular expression.
    * `format` - The regular expression pattern to be used for matching.

  ## Returns

  - `:ok` if the `string` matches the `regex`.
  - `{:error, message}` if the `string` does not match the `regex`.

  ## Examples

      iex> Dsv.Format.validate("string to match", ~r/.*\ .*\ .*/)
      :ok

      iex> Dsv.Format.validate("stringtomatch", ~r/.*\ .*\ .*/)
      {:error, "Value stringtomatch does not match pattern .*\ .*\ .*"}

  """
  def validate(data, format), do: super(data, format)

  @doc """
  The `validate/2` function evaluates whether a given string matches a specified regular expression.

  ## Parameters

    * `data` - The string to be checked against the regular expression.
    * `format` - The regular expression pattern to be used for matching.
    * `message` - An custom error message to be returned in case of failure.

  ## Returns

  - `:ok` if the `string` matches the `regex`.
  - `{:error, message}` if the `string` does not match the `regex`.

  ## Examples

      iex> Dsv.Format.validate("string to match", ~r/.*\ .*\ .*/, "This is wrong.")
      :ok

      iex> Dsv.Format.validate("stringtomatch", ~r/.*\ .*\ .*/, "This is wrong.")
      {:error, "This is wrong."}

      iex> Dsv.Format.validate("stringtomatch", ~r/.*\ .*\ .*/, message: "This is wrong.")
      {:error, "This is wrong."}
  """
  def validate(data, format, message: message),
    do: validate(data, options: format, message: message)

  def validate(data, format, message), do: validate(data, options: format, message: message)
end