Wednesday, September 26, 2012

Validating A Profile field in Drupal (module source of phone field example)

If you have added a profile field like a phone number and want to validate it at the time of registeration of new user account, then here is the code of module(D6) which does exactly that.

First enable profile module and add the field(s), here I've added the field whose machine name is "profile_phone_number" of type textfield.

Firstly create a directory anu_check_phone_profile_field in sites/all/modules and create these two files with the names:

anu_check_phone_profile_field.info

 

; $Id: anu_check_phone_profile_field.info,v 1.1 2012/09/26 09:08:13 D14 Exp $
name = Anu Check Phone Profile field
description =if you've added phone number in the profile field then this will validate it
files[] = anu_check_phone_profile_field.module
core = 6.x
package = custom
; Information added by drupal.org packaging script on 2010-11-12
version = 1.0
core = 6.x

anu_check_phone_profile_field.module

<?php
function anu_check_phone_profile_field_form_alter(&$form, &$form_state, $form_id) {
global $user;
if ($user->uid !=1 and $form_id == 'user_register') {
$form['#validate'][] = 'anu_check_phone_profile_field_validate';
}
}
function anu_check_phone_profile_field_validate($form, $form_state)
{
$ph = trim($form_state['values']['profile_phone_number']);
if(strlen($ph) != 10 or in_array($ph[0],array('1','2','3','4','5','0')) or ! ctype_digit($ph) or preg_match('/([0-9])\1\1\1\1\1/',$ph))
{
form_set_error('profile_phone_number',"Please provide your correct cell number!");
}
}
 
 
That's it go and add the module in admin/build/modules/list and enjoy!


No comments:

Post a Comment