Here is my validator for a phone field in webform module(using hooks of webform validation module). Can u help me in the implementation of clientside validation?

/**
* Implementation of hook_webform_validation_validators().
*/

function potpourri_webform_validation_validators() {
  return array(
    'phonefield' => array(
      'name' => "Phonefield",
      'component_types' => array(
        'textfield',
      ),
			'description' => 'Check phone number'
    )
  );
}

/**
* Implementation of hook_webform_validation_validate().
*/

function potpourri_webform_validation_validate($validator_name, $items, $components, $rule) {
  if ($items) {
		$errors = array();
    switch ($validator_name) {
      case 'phonefield':
				foreach ($items as $key => $val) {
          if ($val && (!isTelefon($val))) {
            $errors[$key] = t("%value is not a telephone.", array('%value' => $val));
          }
        }
        return $errors;
        break;
    }
  }
}


function isTelefon($text) {
	return preg_match('/^(\+){0,1}(\([0-9]+\))?[0-9_\-\/]{6,}$/', str_replace(' ', '', $text));
}

Comments

attiks’s picture

Assigned: Unassigned » Jelle_S
Jelle_S’s picture

In potpourri.module:

/**
 * Implementation of hook_clientside_validation_rule_alter().
 */
function potpourri_clientside_validation_rule_alter (&$js_rules, $element, $context) {
  switch ($context['type']) {
    case 'webform':
      if ($context['rule']['validator'] == 'phonefield') {
        drupal_add_js(drupal_get_path('module', 'potpourri') . '/phone_validator.js');
        $js_rules[$element['element_name']]['phoneField'] = TRUE;
        $js_rules[$element['element_name']]['messages']['phoneField'] = theme('clientside_error', array('message' => 'Field !name must be a valid phone number.', 'placeholders' => array('!name' => $element['element_title'])));
      }
      break;
  }
}

Note: if theme('clientside_error', ...) does not work you have to download the latest dev release and then clear your cache (it's only in since yesterday). Or if you don't want that you can just replace that code with:

  t('Field !name must be a valid phone number.', array('!name' => $element['element_title']));

In phone_validator.js:
(Note that the name of the function is the same as you entered as the key in $js_rules)

//jQuery wrapper
(function ($) {
  //Define a Drupal behaviour with a custom name
  Drupal.behaviors.potpourriAddPhoneValidator = {
    attach: function (context) {
      //Add an eventlistener to the document reacting on the
      //'clientsideValidationAddCustomRules' event.
      $(document).bind('clientsideValidationAddCustomRules', function(event){
        //Add your custom method with the 'addMethod' function of jQuery.validator
        //http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
        jQuery.validator.addMethod("phoneField", function(value, element, param) {
          //return true if valid, false if invalid
          var regexp = /^(\+){0,1}(\([0-9]+\))?[0-9_\-\/]{6,}$/
          return regexp.test(value.replace(' ', ''));
          //Enter a default error message.
        }, jQuery.format('Value must a valid phone number'));
      });
    }
  }
})(jQuery);

I haven't actually tested this code, so there might be a syntax error or so. But I hope you get the general idea. If you have more questions feel free to ask.

mibfire’s picture

Assigned: Jelle_S » Unassigned

Brilliant! it was almost perfect,
i had to modify this return regexp.test(value.replace(' ', '')); to return regexp.test(value.replace(/\s/g, '')); to remove all whitespaces from the string.
The first replace just removed the first whitespace in the phone number.

This is very good module and now is even better.:) Thank You Very Much!!!

Jelle_S’s picture

Component: Code » Documentation

You're welcome, glad I could help :-)
I'll set this to 'documentation', I guess this could be helpful for everyone.

Jelle_S’s picture

Status: Active » Fixed

A documentation page was created for Clientside Validation.

Status: Fixed » Closed (fixed)

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

Anonymous’s picture

Issue summary: View changes

Updated issue summary.