代码之家  ›  专栏  ›  技术社区  ›  Basel Issmail Abdul Hadee

Symfony3-如何验证HTML标记

  •  0
  • Basel Issmail Abdul Hadee  · 技术社区  · 6 年前

    通过使用Symfony验证器
    如何防止一些HTML标记 <input></input> <textarea><textarea>
    从输入字段中输入并保存到数据库中?

    2 回复  |  直到 6 年前
        1
  •  3
  •   OK sure    6 年前

    您可以在实体中的文本/字符串属性上使用regex进行断言。例如,这将阻止字符串中的任何HTML标记:

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

    // 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;
    }
    
        2
  •  0
  •   Parisa    6 年前

    你也可以用 strip_tags

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