How to properly filter a form's data against XSS? Drupal 7.

I've got an (ECK module) entity form. The form's only field is a multi-value field of the field_collection (Field Collection module) type. The field collection contains two fields: a textarea, and a set of radio buttons. The user submits the form (AHAH), the entity is saved and the form is presented back to the user with the submitted values. For this project that is the intended (and necessary) behavior.

My (stripped down) validation handler is as follows:

/**
 * My custom validation handler.
 */
function my_module_eck_entity_form_validate($form, &amp;$form_state) {
  $values = &amp;$form_state['values'];
  $lang = $values['entity']-&gt;language;

  $fields = array('field_my_text', 'field_my_radios');
  foreach ($fields as $field_name) {
    // the values which get saved to the entity object
    foreach ($values['field_my_field_collection'][$lang] as &amp;$item) {
      foreach ($item['entity']-&gt;{$field_name}[$lang] as &amp;$child) {
        $child['value'] = filter_xss($child['value']);
      }
    }

    // the values which get output as part of the form on page-reload
    foreach ($form_state['complete form']['field_my_field_collection'][$lang] as &amp;$item) {
      if (is_array($item) &amp;&amp; isset($item[$field_name][$lang])) {
        foreach ($item[$field_name][$lang] as &amp;$child) {
          if (is_array($child)) {
            $child['value']['#value'] = filter_xss($child['value']['#value']);
          }
        }
      }
    }
  }
}


It works and does what I want, but it is an ugly monstrosity that'll keep me up at night. There has got to be a nicer, cleaner way of doing this.

For the intents and purposes of this question, let's not discuss the pros &amp; cons of Drupal's filter_xss() vs other tools - plenty of existing questions about that.
There's a huge issue with your implementation: it's destructive. Let's say a user writes about HTML, uses common comparison symbols or just uses the evil emoticon for despair: &lt;o&gt;. Changing data will make it harder for the user to later edit his post, it might even remove parts of it. Let's respect the user effort of typing into a textarea and hitting 'Save'.

So, what to do about XSS? Well, XSS is not dangerous in your database, it is only dangerous when displayed in a browser. So relax about saving it and worry about displaying it. Default formatters for text fields will use the text format settings to apply filters. Make sure the text formats available for your user are safe. And if you're writing your own formatter, don't forget to filter the output (preferrably by respecting the text format settings).

See https://drupal.org/node/28984 and https://drupal.org/documentation/modules/filter for more on this topic.