0

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
  • 2
    When you say "some HTML tags" do you mean all HTML tags or specific ones? Commented Sep 28, 2018 at 13:59
  • @OKsure, I mean only specific ones. Commented Sep 28, 2018 at 15:21

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

As per the HTML spec (w3.org), tag name can tonain 0-9,a-z,A-Z and a solidus character "/" before the >. Your regex wouldn't catch the ones that start with 0-9, if there may be in the future? Just a quick observation.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.