I use this module to forbid users type 123456 as phone number.
So I change functions custom_username_validation_username_validate and custom_username_validation_admin to add Custom fieldname and mismatch checkbox.
You can explore my changes, may be optimize and include to your module.

/**
 * Validation function
 *
 * @param mixed $element Posted form structure
 */
function custom_username_validation_username_validate ($element) {
  
  /** Get fieldname from variables */
  $fieldname = variable_get('custom_username_validation_field', 'name');
  
  /** Get mismatch checkbox from variables */
  $mismatch = variable_get('custom_username_validation_mismatch', FALSE);
  
  /** Get username from form elements */
  $username = $element['#post'][$fieldname];

  /** If username not set, do not validate */
  if (!$username)
    return;
  
  /** If pattern not set in module settings, do not validate */
  $pattern = variable_get('custom_username_validation_pattern', '');
  if ($pattern == '')
    return;  
  
  if (!@preg_match($pattern, $username) xor $mismatch)
    form_set_error($fieldname, variable_get('custom_username_validation_errormsg', ''));
}



/**
 * Admin-Settings. Pattern and an error message can be set here.
 */

function custom_username_validation_admin() {

  $form['custom_username_validation_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Field machine name'),
    '#default_value' => variable_get('custom_username_validation_field', 'name'),
    '#description' => t("By default: 'name'")
  );

  $form['custom_username_validation_pattern'] = array(
    '#type' => 'textfield',
    '#title' => t('Pattern to match'),
    '#default_value' => variable_get('custom_username_validation_pattern', ''),
    '#description' => t("See PHP's preg_match() for details. Example: /^0049[1-9]{1}+[0-9]{1,10}$/")
  );

  $form['custom_username_validation_mismatch'] = array(
    '#type' => 'checkbox',
    '#title' => t('Mismatch pattern'),
    '#default_value' => variable_get('custom_username_validation_mismatch', FALSE),
    '#description' => t("Check if field value must mismatch pattern.")
  );

  $form['custom_username_validation_errormsg'] = array(
    '#type' => 'textfield',
    '#title' => t('Error message'),
    '#default_value' => variable_get('custom_username_validation_errormsg', t('Username format is invalid')),
    '#description' => t("Error message that appears in form message collection")
  );
  
  return system_settings_form($form);
}

Comments

Schneck’s picture

Status: Active » Closed (fixed)

you can easily invert patterns using the "!"-operator. or am i misunderstanding something?