Objectives & prerequisites
Objectives
- You will learn how to implement a validation handler.
- You will learn how to set form errors.
Last revision:
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.
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.