Skip to main content
Start of main content.

Drupal 7's positive integer validator

by nick.schuch /

Share this post on social media

Ever written custom code to check if your textfield is a positive integer? I sure have. Then I found an easier way.

In the past I have been required to ensure that a textfield is a positive integer. For these cases I have written a custom element validator and attached it to the field using #element_validate. The below is a paste of the validator rewritten for a custom module called “blog_post”.

/**
 * Custom function to check for positive integer.
 */
function blog_post_integer_validate($element, &$form_state) {
  $value = $element['#value'];
  if (!is_numeric($value) && $value <= 0) {
    form_error($element, t('Please provide a positive integer for %name.', array('%name' => $element['#title'])));
  }
}

After some digging through Drupal 7 core API's I found something even better! I found a validator that does all the heavy lifting for me. This validator is called element_validate_integer_positive. As can be seen it tackles way more edge cases than what mine does and I wish I found it sooner.

function element_validate_integer_positive($element, &$form_state) {
  $value = $element['#value'];
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  }
}

More on this validator and how to implement can be found here: http://api.drupal.org/api/drupal/includes!form.inc/function/element_validate_integer_positive/7