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

matzAB created an issue. See original summary.

jrockowitz’s picture

I recommend using hook_webform_element_alter() or hook_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?"

matzAB’s picture

Hi jrockowitz,

I'll look at it tomorrow and will definitely post a recipe ;)

matzAB’s picture

Status: Active » Needs review
jrockowitz’s picture

Status: Needs review » Fixed

The recipe is great. I actually never thought to use a static class for custom validation callback. I was still using procedural functions.

matzAB’s picture

I 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.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.