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 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
Code explanation
Line 3-7: We define a user schema having
nameandemailas attributes.Line 6:
timestamps()is a function that defines two more functioninserted_atandupdated_at, which Ecto itself manages.
Line 8-14: We also define
changesetfunction 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