Objectives & prerequisites
- You will learn how to implement a validation handler.
- You will learn how to set form errors.
The validation process
Logically, form validation follows the following steps:
- Retrieve the submitted values for which you want to provide custom validation logic.
- Test each of the retrieved submitted values.
- For each value that fails your validation criteria, set a form error.
Example
Assume the following:
- The value you want to test comes from a form field named 'amount'.
- Your logic is: value must be larger than 0 and smaller than 100.
Your pseudo-code will be:
With that out of the way, let's look at how to set form errors.
Setting form errors
You previously researched FormStateInterface and found the setRedirect() method to redirect users. Available through the same interface is the method setErrorByName(), which takes as parameters:
- The name of the field to which the error applies.
- The error message you want to display.
We can now expand our previous example:
Activity
You'll expand your ColourForm class with useful help text and a validation handler that verifies the submitted value is one of several allowed values.
Update your ColourForm class:
- Provide a helpful description for the 'fav_colour field' in your
buildForm()method. Something like 'The colour must be red, green, or blue.' - Implement a validation handler that sets an error if the submitted colour is not red, green, or blue.
1. Setting help text
When you add a field to a form in buildForm(), one of the properties you can set for your field is #description, which shows the description value in a small gray font underneath the form field:
$form['my_field']['#description'] = t("Instructions for this field go here.");2. Testing a value against a range of values
You could use if/then/else statements to test the colour, but if you have a large number of allowed values, the code can become unnecessarily long and irritating to maintain.
PHP provides a built-in function called in_array() to check if a value exists in an array. Follow the link to the documentation to learn how to use this function.
A clean way to check if the submitted value is among a list of predefined values is:
- Create an array with your predefined values:
['red', 'green', 'blue'] - Use
in_array()and pass along your submitted value and your array of predefined values.
For more information and an example on form validation, have a look at the Drupal API Guide on Validating Forms.
Summary
- You implemented a validation handler to add custom validation logic to your form.
- You added a description to a field to provide helpful instructions.