Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a custom validation rule to a model in phoenix framework

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 ?

like image 574
Jeremie Ges Avatar asked Apr 30 '16 23:04

Jeremie Ges


People also ask

What are custom validation rules?

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”.


1 Answers

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
like image 65
Dogbert Avatar answered Jan 04 '23 16:01

Dogbert