JediHelpers. ChangesetHelpers
(jedi_helpers v0.3.0)
Copy Markdown
Provides helper functions for trimming whitespace and validating string fields in Ecto changesets. Particularly useful for ensuring uniqueness and formatting of string inputs before applying database constraints.
Summary
Functions
Trims string changes and converts blank strings to nil by default.
Trims leading and trailing whitespace from one or more string fields in the changeset.
Ensures consistency and helps maintain uniqueness constraints (e.g., on citext fields).
Validates that at least one of the given fields has a non-blank value.
Functions
@spec normalize_strings(Ecto.Changeset.t(), atom() | [atom()], keyword()) :: Ecto.Changeset.t()
Trims string changes and converts blank strings to nil by default.
This is useful for optional form fields where whitespace-only input should be
stored as nil. Non-string fields and fields without a change are left alone.
Set :empty_to_nil to false to retain an empty string after trimming.
Examples
changeset
|> normalize_strings([:first_name, :last_name])
changeset
|> normalize_strings(:reference, empty_to_nil: false)
@spec trim_whitespace(Ecto.Changeset.t(), atom() | [atom()], keyword()) :: Ecto.Changeset.t()
Trims leading and trailing whitespace from one or more string fields in the changeset.
Ensures consistency and helps maintain uniqueness constraints (e.g., on citext fields).
Options
:max(integer): Maximum allowed length after trimming. If exceeded, a validation error is added. Default is 255.:enforce_unique(boolean): When set totrue, adds aunique_constraint/3to the field. Default isfalse.
Examples
changeset
|> trim_whitespace(:username, max: 50, enforce_unique: true)
changeset
|> trim_whitespace(:username, enforce_unique: true)Parameters
changeset(Ecto.Changeset.t()): The changeset containing the field(s) to be processed.field(atom()or[atom()]): The field(s) to trim.opts(keyword()): Options for trimming and validation.
Returns
- An updated
Ecto.Changeset.t()with trimmed values and optional validations.
@spec validate_any_required(Ecto.Changeset.t(), [atom()], keyword()) :: Ecto.Changeset.t()
Validates that at least one of the given fields has a non-blank value.
By default, the error is attached to the first field. Use :error_field and
:message to customize the resulting changeset error.
Example
changeset
|> validate_any_required([:email, :phone],
error_field: :email,
message: "email or phone is required"
)