Forms and validation

You should validate all input data entered in forms. In Zotonic you create forms by writing plain HTML. You can attach one or more validators to each input element. Validators define acceptable values for the input data.

Let’s say you have a required input field ‘title’. To make sure some text is entered in it, attach the presence validator:

<input type="text" id="title" name="title" />
{% validate id="title" type={presence} %}

The validated form field is available to Erlang code using the z_context:get_q_validated/2 function:

Title = z_context:get_q_validated(<<"title">>, Context).

Client- and server-side

Zotonic’s validators work both client- and server-side:

  • JavaScript prevents the form from being submitted until the input data conforms to the validators.
  • All validation is done on the server as well, which protects against users bypassing the validation checks in their browser.

Validators

Zotonic comes with some commonly needed validators:

If you need to implement custom validation logic, use the postback validator. For JavaScript-only custom validation, use the custom validator.

acceptance
Check if an input value evaluates to true.
confirmation
Check if two inputs are the same.
custom
Support for custom client-side (JavaScript-based) validators.
date
Validate input date against a given date format.
email
Check if the content of the input field is an e-mail address.
email_unique
Check if an entered e-mail address is unique, by looking in the m_identity table for the email key:
format
Regular expression test.
length
Check the length of a text input.
name_unique
A validator to check whether a resource’s name is unique:
numericality
Numerical input and range check.
postback
Performs a custom server side validation of an input value. This allows you to add your own validation logic to HTML form fields.
presence
Check if an input has been filled in or checked.
username_unique
Check if an entered username is unique, by looking in the m_identity table for the given username:

Icons Developer Guide Search

Referred by

Modules

Modules are the building blocks of Zotonic. They add functionality to your Zotonic website such as:

name_unique

A validator to check whether a resource’s name is unique:

acceptable_password

A validator to check whether a password conforms to the password secutiry requirements.

hasedge

A validator to check if a resource has a certain number of edges with a predicate.