ExEssentials.BrazilianDocument.Changeset (ExEssentials v0.7.0)

View Source

Provides Ecto.Changeset validators for Brazilian CPF and CNPJ documents.

This module offers three helper functions to easily validate fields within an Ecto changeset:

## Examples

  import Ecto.Changeset

  alias ExEssentials.BrazilianDocument.Changeset

  changeset =
    %User{}
    |> cast(%{"cpf" => "39053344705"}, [:cpf])
    |> Changeset.validate_cpf(:cpf)

  changeset.valid?
  #=> true

Summary

Functions

Validates a field as either CPF or CNPJ, depending on the value. Uses ExEssentials.BrazilianDocument.Validator.valid?/1 under the hood.

Validates a field as a valid CNPJ (Cadastro Nacional da Pessoa Jurídica).

Validates a field as a valid CPF (Cadastro de Pessoas Físicas).

Functions

validate_brazilian_document(changeset, field, opts \\ [])

@spec validate_brazilian_document(
  changeset :: Ecto.Changeset.t(),
  field :: atom(),
  opts :: keyword()
) ::
  Ecto.Changeset.t()

Validates a field as either CPF or CNPJ, depending on the value. Uses ExEssentials.BrazilianDocument.Validator.valid?/1 under the hood.

## Parameters

- changeset: an `Ecto.Changeset` struct.
- field: the atom representing the field name.
- opts: an optional keyword list. Accepts `:message` to override the default error message.

## Examples

  iex> validate_brazilian_document(changeset, :document)
  iex> validate_brazilian_document(changeset, :document, message: "is invalid")

validate_cnpj(changeset, field, opts \\ [])

@spec validate_cnpj(
  changeset :: Ecto.Changeset.t(),
  field :: atom(),
  opts :: keyword()
) ::
  Ecto.Changeset.t()

Validates a field as a valid CNPJ (Cadastro Nacional da Pessoa Jurídica).

## Parameters

- changeset: an `Ecto.Changeset` struct.
- field: the atom representing the field name.
- opts: an optional keyword list. Accepts `:message` to override the default error message.

## Examples

  iex> validate_cnpj(changeset, :company_cnpj)
  iex> validate_cnpj(changeset, :company_cnpj, message: "is invalid")

validate_cpf(changeset, field, opts \\ [])

@spec validate_cpf(
  changeset :: Ecto.Changeset.t(),
  field :: atom(),
  opts :: keyword()
) ::
  Ecto.Changeset.t()

Validates a field as a valid CPF (Cadastro de Pessoas Físicas).

## Parameters

- changeset: an `Ecto.Changeset` struct.
- field: the atom representing the field name.
- opts: an optional keyword list. Accepts `:message` to override the default error message.

## Examples

  iex> validate_cpf(changeset, :cpf)
  iex> validate_cpf(changeset, :cpf, message: "is invalid")