In D7, a module could implement hook_form_alter() to add to a form being built. And you could use:

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

to cause my_validation_function(...) to be called to do custom validation on submission.

In D8, hook_form_alter() (and hook_form_formid_alter()) work the same, but I haven't figured out how to get custom validation to happen. When I attempt the D7 approach, I get "The website encountered an unexpected error..."

I've tried api.drupal.com, but can't find any information on this at all. Anyone have any pointers?

Comments

dwillcox’s picture

D'oh! I think I found it. It seems I had neglected to do

use Drupal\Core\Form\FormStateInterface;

in the file with the validation function. Apparently, php doesn't complain when you reference an undefined type in defining a function, only when you try to call the function.

Sorry, I'm more comfortable with java, which is much more anal about types.

XLD’s picture

To get custom validation to happen you will have to create a hook_form_alter but it should work with other form alter hooks aswell to add your custom validation to the validate array.

Once added, create your function and do your validation.

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

// Add a new validation function.

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

}

function mymodule_node_form_submit($form, FormStateInterface $form_state) {

// Do your validation.

}