I see all kinds of examples of how to add a custom validator to an "existing form." Which means, you would use hook_form_alter. I want to add one in the code for my custom form.

I'm adding this in my buildForm():

$form['#validate'][] = 'mycustom_form_validate';

However, that function never seems to get called. I know naming the validation function "validateForm()" would make it work automatically. But I want to specifically call this validation function because things are going to get more complex. But I seem stuck on this baby step.

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#attributes']['novalidate'] = 'novalidate';
    $form['#cache']['max-age'] = 0;
    $form['#action'] = '#email_subscription';
    $form['#validate'][] = 'mycustom_form_validate';

    $form['fname'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First Name'),
      '#maxlength' => 255,
      '#size' => 64,
      '#required' => TRUE,
      '#required_error' => 'Please provide your first name.',

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('send'),

    return $form;

  public function mycustom_form_validate(array &$form, FormStateInterface $form_state) {
    $valid = $this->validateEmail($form, $form_state);
    if (!$valid) {
      $form_state->setErrorByName('email', $this->t('Invalid email address.'));

1 Answer 1


You just need to change the line to:

$form['#validate'][] = '::mycustom_form_validate';

Drupal has special handling for that :: prefix (see FormState::prepareCallback), and processes the above to an equivalent callback of:

[$form_object, 'mycustom_form_validate']

Which will correctly resolve to your custom method.

  • That got it. Thank you for the explanation.
    – xpersonas
    Aug 23, 2019 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.