Symfony3 - How to validate HTML tags

1.3k Views Asked by At

By using Symfony validators
How to prevent some HTML tags like <input></input> <textarea><textarea>
from being entered in input field and saved in database?

2

There are 2 best solutions below

1
On BEST ANSWER

You can assert using regex on text/string properties in your entity. For example, this should block any HTML tags in a string:

// src/Entity/Thing.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Thing
{
    /**
     * @Assert\Regex(
     *     pattern="/<[a-z][\s\S]*>/i",
     *     match=false,
     *     message="Your text cannot contain HTML"
     * )
     */
    protected $text;
}

This should check for input and textarea elements:

// src/Entity/Thing.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Thing
{
    /**
     * @Assert\Regex(
     *     pattern="/<(?=.*? .*?\/ ?>|textarea|input)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i",
     *     match=false,
     *     message="Your text cannot contain certain HTML tags"
     * )
     */
    protected $text;
}
0
On

also you can use strip_tags php function in your setter function to prevent html tags, also you can pass some allowed tags to this function.

public function setText()
{
    $this->text = strip_tags($text);
    return $this;
}