You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式验证字符串问题:现有规则无法匹配含空格的可空字符串

Fixing Your Regex Validation for NameProj

Your current regex has two key issues that are preventing it from working as intended:

  1. Missing support for spaces: Your pattern only matches uppercase/lowercase letters (a-zA-Z), but you specified the input should allow spaces.
  2. No start/end anchors: The regex /[a-zA-Z]{0,255}/ will match any substring of letters in the input, not the entire string. This means invalid characters (like numbers or symbols) would still pass validation as long as there’s at least one letter present.

Here’s the corrected annotation with a proper regex:

/**
 * @var string
 *
 * @Assert\Regex(
 *     pattern="/^[a-zA-Z\s]{0,255}$/",
 *     match=true,
 *     message="NameProj is invalid. It can only contain letters, spaces, and be up to 255 characters long."
 * )
 *
 * @ORM\Column(name="NameProj", type="string", length=255, nullable=true)
 */
private $NameProj;

Breakdown of the corrected regex:

  • ^ = Anchors the match to the start of the string
  • [a-zA-Z\s] = Matches any uppercase letter, lowercase letter, or whitespace (if you only want regular spaces and not tabs/newlines, replace \s with a single space )
  • {0,255} = Allows between 0 and 255 of the allowed characters (so empty input is permitted, aligning with your nullable field)
  • $ = Anchors the match to the end of the string, ensuring the entire input is validated against the pattern

I also removed the trailing space in name="NameProj " in the @ORM\Column annotation—this was likely a typo that could cause unexpected issues with your database column mapping.

内容的提问来源于stack exchange,提问作者Julie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:29:20