Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Hello,
I wonder what's the best way to add a custom validation to any field in my forms? Should I use a handler, a hook or something different? Let's say, I have a custom user registration form with some profile fields added. I need to check the username and email for uniqueness. I know that I can use the unique checkbox in webform configuration. But that only checks against previously posted values for this form. It doesn't check the user table from Drupal. I also want to validate a user password (length and password policy).
How should I do that?
Thanks for your help!
Comments
Comment #2
jrockowitz CreditAttribution: jrockowitz as a volunteer and at The Big Blue House commentedI recommend using
hook_webform_element_alter()
orhook_webform_element_ELEMENT_TYPE_alter()
and adding a #element_validate callback.@see http://cgit.drupalcode.org/webform/tree/webform.api.php
Once you figure this out, could please post a recipe about "How to add custom validation to a webform element?"
Comment #3
matzAB CreditAttribution: matzAB commentedHi jrockowitz,
I'll look at it tomorrow and will definitely post a recipe ;)
Comment #4
matzAB CreditAttribution: matzAB commentedRecipe can be found here: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-ad...
Comment #5
jrockowitz CreditAttribution: jrockowitz as a volunteer and at The Big Blue House commentedThe recipe is great. I actually never thought to use a static class for custom validation callback. I was still using procedural functions.
Comment #6
matzAB CreditAttribution: matzAB commentedI wanted to separate the validation callback from the module file to keep the code clean. That was the best way to do it ;)
Thanks for convincing me to write the recipe. I'm quite new to the "Drupal world" and looking forward to contribute more and more.