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 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.
Following is an example of defining a scheme.
defmodule Form.User douse Ecto.Schemaschema "user" dofield :name, :stringfield :email, :stringtimestamps()enddef changeset(user, attrs) douser|> cast(attrs, [:name, :email])|> validate_required([:name, :email])|> validate_format(:email, ~r/@/)|> unique_constraint(:email)endend
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.
Using the Ecto schema like above, we can validate a form by checking all the constraints that is required for form validation.
Free Resources