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?
-
2When you say "some HTML tags" do you mean all HTML tags or specific ones?OK sure– OK sure2018-09-28 13:59:08 +00:00Commented Sep 28, 2018 at 13:59
-
@OKsure, I mean only specific ones.Basel Issmail– Basel Issmail2018-09-28 15:21:11 +00:00Commented Sep 28, 2018 at 15:21
Add a comment
|
2 Answers
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;
}
1 Comment
Raid
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.
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;
}