与任何html标记都不匹配的正则表达式

Ana*_*ion 2 c# regex asp.net-mvc unobtrusive-validation

我对regexp真的很不好,我想要的是一个不匹配任何html标记(用于用户输入验证)的regexp。

我想要的是负面的:

<[^>]+>
Run Code Online (Sandbox Code Playgroud)

我现在有的是

public class MessageViewModel
{
    [Required]
    [RegularExpression(@"<[^>]+>", ErrorMessage = "No html tags allowed")]
    public string UserName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但这与我想要的相反-只能使用html标签的用户名

Tom*_*lak 5

正则表达式不能进行“负”匹配。

但是他们可以进行“正”匹配,然后您就可以将找到的所有内容排除在字符串之外。


编辑-更新问题后,事情变得更加清晰了。尝试这个:

public class MessageViewModel
{
    [Required]
    [RegularExpression(@"^(?!.*<[^>]+>).*", ErrorMessage = "No html tags allowed")]
    public string UserName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

说明:

^            # start of string
(?!          # negative look-ahead (a position not followed by...)
  .*         #   anything
  <[^>]+>    #   something that looks like an HTML tag
)            # end look-ahead
.*           # match the remainder of the string
Run Code Online (Sandbox Code Playgroud)

  • 不要将事物(如HTML标记)列入黑名单,而应考虑将其列入白名单。这样安全得多,维护起来也容易得多。`[[RegularExpression(@“ ^ [\ p {L} \ p {N}] + $”,ErrorMessage =“仅字母和数字。不允许使用空格。”)]`请参见http://www.regular-expressions。 info / unicode.html可帮助您选择正确的Unicode字符范围。此““ ^ [a-zA-Z0-9] + $”`的非Unicode版本。 (2认同)