Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Plugins

Strip HTML from Form textarea field such as Email message

form

Solved by pamtbaau View solution

Started by David 6 years ago · 2 replies · 707 views
6 years ago

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.

6 years ago Solution

@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:
    YAML
    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:
    PHP
    public function onFormPrepareValidation($event) {
     $message = $event['form']->getData('message');
     $event['form']->setData('message', strip_tags($message));
    }
    
👍 1
last edited 08/11/20 by pamtbaau
6 years ago

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 👍

Suggested topics

Topic Participants Replies Views Activity
Plugins · by Rene, 1 week ago
2 42 1 week ago
Plugins · by Xavier, 4 weeks ago
2 53 4 weeks ago
Plugins · by Luka Prinčič, 7 years ago
3 1179 1 month ago
Plugins · by Sebastian van de Meer, 1 month ago
1 47 1 month ago
Plugins · by PIERROT Alain, 2 months ago
3 71 2 months ago