Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Introduction
"Validators" allows you to use the Symfony Validator component inside your Drupal projects. The module allows you to extend your forms with an extra parameter called #validators
. This validator is designed to validate forms against constraints (i.e. rules). An overview of these constraints can be found on the official component page.
Requirements
- PHP Version: 5.3.x or greater.
API Hooks
- hook_validator_asserts: Introduce custom validator assertions to the form validator.
Example
In the following example we will validate if the user filled in a valid e-mail address and a valid ISBN number:
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Contribute form.
*/
class TestForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return mymodule_example_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['iban'] = array(
'#type' => 'textfield',
'#title' => t('Bank account (IBAN format)'),
'#validators' => array(
'Iban' => array(
'message' => t(
'This value is an invalid bank account number. Please respect the <a href="@url">IBAN format</a>.',
array('@url' => 'https://en.wikipedia.org/wiki/https://en.wikipedia.org/wiki/International_Bank_Account_Number')
),
)
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
Supporting organizations:
sponsored development of this module
Project information
- Module categories: Developer Tools
- 16 sites report using this module
- Created by legovaer on , updated
- Stable releases for this project are covered by the security advisory policy.
Look for the shield icon below.
Releases
7.x-1.0
released 31 May 2016
Works with Drupal: 7.x
✓ Recommended by the project’s maintainer.
Development version: 7.x-1.x-dev updated 8 Jun 2016 at 11:45 UTC