Search code examples
elixirphoenix-frameworkecto

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 ?


Solution

  • 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