symfonysymfony3symfony-validator

Symfony3 - How to validate HTML tags


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?


Solution

  • 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;
    }