Validating form data
All forms must implement the \Drupal\Core\Form\FormInterface
. The interface defines a validation
method. The validateForm
method is invoked once a form has been submitted and provides a way to validate the data and halt the processing of the data if required. The form state object provides methods for marking specific fields as having the error, providing a user experience tool to alert your users to specify the problem input.
In this recipe, we will be validating the length of the submitted field.
Getting ready
This recipe will use the module and custom form created in the first Creating a form recipe.
How to do it...
- Open and edit the
\Drupal\drupalform\Form\ExampleForm
class in thesrc/Form
directory of the module.
Â
- Before validating the
company_name
value, we will need to check whether the value is empty using theisValueEmpty()
method from the\Drupal\Core\Form\FormStateInterface
object:
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface...