When people copy/paste into a wysiwyg it will sometimes paste with html formatting, and as a result add additional characters (html entities). This is taking up the character limit on some of my fields, so I want to try and get rid of these characters and then send it to validate. I've tried making my custom validation function but it still goes through the default validation before my custom one. Is there a way to check for character limit after a user clicks "preview" but before validation?

Thanks

Comments

joshi.rohit100’s picture

you can call your validation first before default validation using array_unshift(), then you can change value using form_set_value()

Jaypan’s picture

An example of what Joshi is saying is as follows. First, look at the original form definition (an example):

function some_form($form, &$form_state)
{
  $form['textfield'] = array
  (
    '#type' => 'textarea',
    '#title' => t('Enter some text.'),
  );
  $form['submit'] = array
  (
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

We then add our own validation handler in hook_form_alter() to be run before any of the default handlers:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'some_form')
  {
    if(!is_array($form['#validate'])
    {
      $form['#validate'] = array();
    }
    array_unshift($form['#validate'], 'my_module_custom_validate');
  }
}

And then we make our changes in our custom validation handler, that will now be run before any of the default validation handler and submit functions:

function my_module_custom_validate($form, &$form_state)
{
  $submitted_value = $form_state['values']['textfield'];
  // collapse multiple spaces to a single space (as an example):
  $clean_value = preg_replace('/  +/', ' ', $submitted_value);
  // save the cleaned up value back to the element:
  form_set_value($form['textfield'], $clean_value, $form_state);
}
pub497’s picture

I tried the solutions above but it kept giving me the character limit error.
What I ended up doing was clearing the error in my validate function, filtering the text, and recheck if it is still above the limit and setting my own error message if it still is

Jaypan’s picture

There was probably something wrong with your code.

sandu.camerzan’s picture

If you want a certain element to skip core validation and just be validated by your own validation function, set the validated param to TRUE:

      $element['form_element'] = array(
        '#type' => 'select',
        '#title' => t('SKU'),
        '#options' => $options,
        '#default_value' => $default_value,
        '#validated' => TRUE,  // Important - skip default validation.
        '#weight' => 50
      );