Strip HTML from Form textarea field such as Email message

What is the best way to strip HTML from a Form text or textarea field? Specifically, I’m getting manual spam entered into the message box of my Contact form.

@squirrel, I can think of two avenues:

  • Field validation using Regex:
    Add a validation to the field which will fail when its content contains an anchor. A simple example:
    validate:
      type: textarea
      pattern: '^(.(?!<a))*$'  # Any charactor must not be followed by '<a'
      required: true
    
    The form validation will fail on input like “This field contains an <a href=”…"> in its text".
  • Cleanup textarea:
    A custom plugin could respond to event onFormPrepareValidation and sanitise the data of the form. Eg. when the email form uses field ‘message’ as body, its field data could be cleansed as follows:
    public function onFormPrepareValidation($event) {
       $message = $event['form']->getData('message');
       $event['form']->setData('message', strip_tags($message));
    }
    
1 Like

Thank you so much @pamtbaau
The form validation was just what I was looking for. I didn’t find much on syntax for the validate before I posted. A regex pattern works great!
Thanks again :+1: