- Open and edit the \Drupal\drupalform\Form\ExampleForm class in the src/Form directory of the module.
- Before validating the company_name value, we will need to check whether the value is empty using the isValueEmpty() method from the \Drupal\Core\Form\FormStateInterface object:
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('company_name')) {
// Value is set, perform validation.
}
}
- The \Drupal\Form\FormStateInterface::isValueEmpty method takes the key name of the form element; for example, $form['company_name'] from the buildForm method is referenced through company_name in the isValueEmpty method.
- Next, we will check whether the value's length is greater than five:
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('company_name')) {
if (strlen($form_state->getValue('company_name')) <= 5) {
// Set validation error.
}
}
}
- The getValue takes a form element's key and returns the value. Since we have already verified that the value is not empty, we can retrieve the value.
If you had any experience with previous versions of Drupal, note that the form state is now an object and not an array.
- If the logic check finds a value with a length of five or fewer characters, it will throw a form error to prevent submission:
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('company_name')) {
if (strlen($form_state->getValue('company_name')) <= 5) {
$form_state->setErrorByName('company_name', t('Company name is less than 5 characters'));
}
}
}
We can place the setErrorByName method in our strlen logic check. If the string is fewer than five characters, an error is set on the element. The first parameter is the element's key, and the second parameter is the message to be presented to the user.
- When the form is submitted, the Company name text field will have more than five characters or be empty to be submitted.
