Reputation: 11780
I want to validate the input of a form before saving it to database to prevent Sql Injection and XSS.
I don't want to modify the code of the module directly so I've created a custom module to do this kind of stuff but I'm not exactly sure how to use the #validate element to call a validation function.
In my custom module, I have this function with this logic implemented:
function mymodule_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'myform':
drupal_set_message('this message is printed :D');
$form['#validate'] = array('my_validation_function');
break;
}
}
function my_validation_function($form, &$form_state) {
drupal_set_message('not printed :(');
watchdog('not printed :___(', 'not printed :___(');
}
I don't know exactly how it works but It seems that the second function is never called when I submit the form.
EDIT (SOLUTION):
I've finally found where the validation was placed in the module:
$form['mod_name']['submit']['#validate'][] = 'my_validation_function';
I thought that just adding form['#validate'] would work despite of the contents on $form variable, but seems that depending on the implementation of the module if you don't place the #validate element where it is expected it is ignored.
Upvotes: 2
Views: 4080
Reputation: 37978
Be careful of replacing the #validate key as you will replace any other validators that have been added before you.
Best to append your function to it;
$form['#validate'][] = 'my_validation_function';
Upvotes: 5