I have a content type with a Float field. When my users accidentally enter (or copy/paste) a value with trailing whitespace (e.g. "11 "), drupal gives them the ugly error message:

Only numbers and the decimal separator (.) allowed in Weight.

But this should be a very easy thing to solve and is not something to bother the user with. However, I can't seem to figure out how to interject code from my module at the right place in order to trim() the value before drupal does its field validation.


1 Answer 1


Add the following to a custom module:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'BUNDLE_NAME_node_form'){
    $language_float = $form['MACHINE_NAME_FIELD']['#language'];
    $form['MACHINE_NAME_FIELD'][$language_float]['#after_build'][] = 'MYMODULE_field_float_rectify';

function MYMODULE_field_float_rectify($element, &$form_state) {
  $children = element_children($element);
  foreach($children as $child){
    $element[$child]['value']['#value'] = trim($element[$child]['value']['#value']);
  return $element;

I would think you can also add it to your admin theme's template.php file, but it seems to be more appropriate to add it to a module.

  • I tried this, but drupal seemed to be noticing the "bad" float value before this code was run, so it would still reject my submission and display the original error message. Jan 14, 2015 at 20:42
  • That is strange as this code should run before all validation handlers. Just double-check and clear the cache. Jan 15, 2015 at 6:42

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.