Module Development

Add a Validation Callback to an Existing Form for Drupal 8, 9, and 10

When working with forms that are not created by your code, where you're not implementing the form controller but rather interacting with the form via implementations of hook_form_alter(), you can use the #validate property of the root form element to add additional validation logic in the form of a callback function or method.

In this tutorial we'll:

  • Implement a #validate callback that raises an error if specific conditions are not met

By the end of this tutorial you should know how to add custom validation logic to any form in Drupal by using a #validate callback.

Drupal Module Development