What is form validation in Phoenix?

Form validation entails checking whether the user input submitted through the web page is correct and meets certain conditions. Form validation is essential to prevent users from submitting incorrect or invalid data.

Phoenix provides us with the facility of form validation by providing us with a database wrapper known as Ecto.

Ecto: database wrapper

Ecto schema is a database wrapper that allows us to interact with the database by mapping the elixir values to external data sources and vice versa. Ecto provides us with validation based on schema definition. A schema describes data shape by field names and their data types.

Code example

Following is an example of defining a scheme.

defmodule Form.User do
use Ecto.Schema
schema "user" do
field :name, :string
field :email, :string
timestamps()
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
end
end

Code explanation

  • Line 3-7: We define a user schema having name and email as attributes.

    • Line 6: timestamps() is a function that defines two more function inserted_at and updated_at , which Ecto itself manages.

  • Line 8-14: We also define changeset function that casts the attributes to the schema, validates the name and email field required, email is valid or not, and ensures whether the email field is unique or not.

Conclusion

Using the Ecto schema like above, we can validate a form by checking all the constraints that is required for form validation.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved