With a custom form, how to sanitize user input before query gets to URL? I followed this tutorial to create a custom Search form that takes users to the main search page with a query in the URL (meaning it uses a get method). This gives me more flexibility than using an exposed filter, so I'd like this to work. One thing that I want to do, however, is make sure that if someone searched:

&lt;script&gt;alert('foo')&lt;/script&gt;


that the query in the URL would not have the tags included. Drupal has plenty of sanitization functions, so I'm not worried about that. But I can't figure out WHERE in the custom form plugin I would actually add the sanitization.

Please help! I've included the code of my plugin below:

&lt;?php

namespace Drupal\my_custom_search\Plugin\Form;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyCustomSearchForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'site_search_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#action'] = '/search';
    $form['#method'] = 'get';
    $form['#attributes']['class'][] = 'usa-search';
    $form['#attributes']['class'][] = 'usa-search-big';

    $form['fulltext_search'] = [
      '#type' =&gt; 'search',
      '#attributes' =&gt; [
        'id' =&gt; array('search-field-big'),
        'size' =&gt; '',
        'maxlength' =&gt; '',
      ],
      '#prefix' =&gt; '',
      '#suffix' =&gt; '',
    ];

    $form['actions']['submit'] = [
      '#type' =&gt; 'submit',
      '#value' =&gt; $this-&gt;t('Search'),
      '#button_type' =&gt; 'search',
      '#attributes' =&gt; [
         'class' =&gt; ['usa-search-submit-text'],
      ],
      '#name' =&gt; '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &amp;$form, FormStateInterface $form_state) {

  }

}


UPDATE: I ended up adding 'pattern' =&gt; '[^/&gt;&lt;\][\\\x22,;|]+', in the attributes array, and this at least prevents submission of text with characters I don't want. I may still try to find a JS solution that works better for the user.
Drupal's mantra is to sanitise upon output, not input. See Writing secure code for Drupal 8 for more information. 

So there's no need to sanitise upon submission, just make sure that if you're rendering that value anywhere, it's done in a secure manner (as explained in the docs above).

If you decide that you still need the solution you've outlined, it's going to have to be implemented in JavaScript. Your form method is GET so the browser handles the input -> URL conversion, not Drupal.