Drupal 7 : How to add custom validation to an existing Drupal node form

 Form validation is an essential part of any web system. You need to ensure that the user has added valid data and if not, show them a meaningful error message. Validation functions are normally implemented in the module where the form is defined. However, thanks to Drupal’s hook system, you can add a validation function to any Drupal form, even if you did not create the form.


Alter the form

 

To add the new validation function, you need to alter the form. You can do this by implementing hook_form_alter().

function custom_code_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'registration_form_node_form') {
    $form['#validate'][] = 'starting_registraion_email_validate';
  }
} 


In the above code, we are first checking that the form id is registration_form_node_form.

$form['#validate’] is a form element which lists all of the validation functions for a given form.

Create the validation function

You need to add your validation function to that array by adding the following: $form['#validate'][] = ‘starting_registraion_email_validate’. $form[‘validate’] is an array and you can add to that with $form['#validate'][].


function starting_registraion_email_validate(&$form, &$form_state, $form_id) {
        $valss = $form_state['input']['field_email_mem_info']['und'][0]['email'];
	$query11 = db_select('field_data_field_email_mem_info', 'emaild');
	$query11->fields('emaild', array('bundle'));
	$query11->condition('emaild.field_email_mem_info_email', $valss);
	$result11 = $query11->execute();
	$num_of_results = $result11->rowCount();
	if($num_of_results > 0) {
		form_set_error('Email', t('Email id already register'));
	}
} 


You will see there are now two validation handlers, the core node_form_validate and the one that you added, starting_registraion_email_validate.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...