1

A particular form field can be left blank or filled with digits, with no other valid characters including dash"-"

$form['hours'] = array(
    '#type' => 'textfield',
    '#title' => t('Hours worked per week'),
    '#size' => 3, 
    '#maxlength' => 3, 
    '#default_value' => '',
    '#rules' => array(
      "digit",
      'length[0, 3]',
    ),
    '#filters' => array('numeric', 'trim')
  );

I have a minimum length of 0, but an empty field appears to be invalid. I've tried using "numeric" instead of "digit" but this allows dashes.

Is there some way to do this without using a custom handler?

1
  • you can always use javascript... have you looked into building a quick client-side js validation? Commented Mar 30, 2013 at 6:06

1 Answer 1

3

The way I did this was to add a custom validation handler. I know I asked for a solution without one, but it turned out to be a fairly simple thing to do. See the "#element_validate' array element below.

$form['hours'] = array(
  '#type' => 'textfield',
  '#title' => t('Hours worked per week'),
  '#size' => 3, 
  '#maxlength' => 3,
  '#element_validate' => array('mymodule_validate_integer'),
  '#default_value' => '',
  '#rules' => array(),
  '#filters' => array('numeric', 'trim')
);

function mymodule_validate_integer($element, &$form_state, $form) {
  if (!empty($element['#value']) && (!is_numeric(parse_size($element['#value'])) || $element['#value'] < 0)) {
    form_error($element, t('"!name" must be a positive number.', array('!name' => t($element['#title']))));
   }
 }


function mymodule_clientside_validation_rule_alter(&$js_rules, $element, $context) {
switch($context['type']) {
case 'element_validate':
  if (in_array('mymodule_validate_integer', $context['functions'])) {
    _clientside_validation_set_minmax(
        $element['#name'], 
        $element['#title'], 
        0, 
        99999, 
        $js_rules, 
        t('"!name" must be a positive number.', array('!name' => t($element['#title'])))
    );
  }
  break;
  } 
}

I hope this helps someone in the future.

2
  • This is a common method for doing form validation. But, then it is a server side method.
    – AjitS
    Commented Apr 2, 2013 at 8:13
  • Sorry I had not copy and pasted in the full answer. Posts crossed. I have updated my answer.
    – Rob
    Commented Apr 2, 2013 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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