I am creating some theme settings and am creating a form to populate them in theme-settings.php. I am using the hook hook_form_system_theme_settings_alter().

I would like to restrict or verify that only numbers can be entered into a field. I've searched online but have not found how to do this. Would anyone know what I ought to add to my code?

Code currently looks like:

$form['mysite_theme']['mysite_contact_phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Contact Number'),
    '#default_value' => $default['mysite_contact_phone'],
    '#description' => t('Enter the main contact number for this site.'),
    '#required' => TRUE,

2 Answers 2


You should be able to add your own validation handler. After the code you've shown, add this:

$form['#validate'][] = 'my_validation_handler';

Then in your handler, you can add your own validation:

function my_validation_handler($form, &$form_state)
    form_set_error('mysite_contact_phone', t('Contact number must be numeric'));
  • Ah thanks! I was almost about to close this as I found '#element_validate' => array('element_validate_number'), but only just relised this wont allow spaces.
    – MeltingDog
    Apr 20, 2017 at 1:33
  • Sorry, I'm having difficulty getting this to work. I'll close this and create a new ticket.
    – MeltingDog
    Apr 20, 2017 at 1:44
  • You mean you want to allow numbers and spaces?
    – Jaypan
    Apr 20, 2017 at 1:51
  • Eventually, yes, but I want to try to get it working with just numbers first (currently with the above nothing happens).
    – MeltingDog
    Apr 20, 2017 at 1:52
  • There is a good chance that the value is not stored in $form_state['values']'mysite_contact_phone']. Many admin forms in Drupal have the value nested deeper, so you should dump the entire $form_state['values'] variable to find the actual location of the submitted data.
    – Jaypan
    Apr 20, 2017 at 1:54

You can use Elements module to get a HTML5 number field.

Your Answer

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

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