I want to add a custom validation rule in my ecto model.
Let's say I have this code:
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> validate_length(:description, min: 280)
|> my_awesome_validation(:email)
end
def my_awesome_validation(email) do
# ??
end
What should I write in my_awesome_validation function to throw an error and so on ?
Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record. A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of “True” or “False”.
The way you're piping into my_awesome_validation
, it'll get changeset
as the first argument and the atom :email
as the second.
This is how you would validate if the given field contains at least one @
:
def my_awesome_validation(changeset, field) do
value = get_field(changeset, field)
if value =~ "@" do
changeset
else
add_error(changeset, field, "does not contain '@'")
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With