1

I have a custom node-creation form for which I have my own validation function. How can I make sure that after my validation function the form goes through the same validation that it would have done on the original node-creation form?
Some thing like node_validate looks like the kind of thing I need, but it works on $node objects rather than forms.
The order of operations I perceive to be the best is

  1. On submit run custom validation
  2. If custom validation passes run the normal node validation
  3. If node validation succeeds insert values in the database

Is that a good and Drupal way?

  • Apparently node_validate() is useless on a custom form because the errors get displayed but aren't acted on. There doesn't seem to be a way to catch the errors, even with form_get_errors(). – htoip Jun 20 '12 at 12:53
2

If your form has a structure similar to the one used for the node edit form, then you can use node_validate(), which is called from the form validation handler for the node edit form.

function node_form_validate($form, &$form_state) {
  node_validate($form_state['values'], $form);
}

node_validate() converts the first argument in an object using the following code.

  // Convert the node to an object, if necessary.
  $node = (object) $node;
  $type = node_get_types('type', $node);

Your form validation handler's code should be similar to the following one.

function mymodule_form_validate($form, &$form_state) {
  // Run your validation code.
  node_validate($form_state['values'], $form);
}

As general rule, the validation code should go in the form validation handler. If the form validation handler set any error, the form submission handler is not called, and the user is returned to the form to correct what is wrong in the data that has been submitted.

  • I was surprised that I could pass $form to node_validate() when it's expecting a $node. – htoip Jun 16 '12 at 18:45
  • $form is necessary for node_validate(), as it is the parameter required from hook_validate(), and hook_nodeapi('validate') (hook_node_validate() in Drupal 7), which are invoked by node_validate(). – kiamlaluno Jun 16 '12 at 18:50
  • CAN YOU say how to do it in drupal 7 – Lucifer Sep 5 '14 at 5:45
1

node_validate() will solve the problem. The original validation process will not be affected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.