Custom validation on a views field plugin options form

Submitted by charles on

When validating an options form for a views field plugin class that extends FieldPluginBase, you need to add a `validateOptionsForm()` function and use an array for getting the value although when setting the error you don't need to include 'options':

/**
 * {@inheritdoc}
 */
public function validateOptionsForm(&$form, FormStateInterface $form_state): void {
  parent::validateOptionsForm($form, $form_state);
  // Ensure that an Aria label is filled in if the button label is displayed.
  if ($form_state->getValue(['options', 'button_label_visibility']) && empty($form_state->getValue(['options', 'aria_label']))) {
    $form_state->setError($form['aria_label'], nt('Aria label is required when the button label is shown.'));
  }
}

Note, I found that using $form_state->setErrorByName did not work for me, so I used setError() instead.