mvc数据注释,以限制用户不允许数字和特殊字符

时间:2015-01-28 13:44:24

标签: regex asp.net-mvc-4 data-annotations

我正在尝试验证用户的输入,只插入字母数字字符,包括。,_ white space等特殊字符。

Point 1. the user cant insert only special characters like @@@@@@@ or .........
Point 2. or any numeric numbers like 2222222.

它应该是任何有效的格式,如。 "hi i am asking a question on stack overflow.this is my 11th attempt. "

我尝试了这些表达,但它不允许我像第1点和第2页那样限制用户,请帮忙。

这是我的代码

[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid User Name")]
        public string UserName { get; set; }
        [Required]
        [StringLength(250, MinimumLength = 5, ErrorMessage = "User Description must have minimum 5 and maximum 250 characters.")]
        [RegularExpression(@"^[^<>!@#%/?*]+$", ErrorMessage = "Invalid User Description")]
        public string Description { get; set; }

2 个答案:

答案 0 :(得分:3)

您需要在开始时使用否定前瞻。

@"^(?![\W_]+$)(?!\d+$)[a-zA-Z0-9 .&',_-]+$"

DEMO

  • (?![\W_]+$)否定前瞻断言字符串不会包含特殊字符。

  • (?!\d+$)断言字符串不会只包含数字。

答案 1 :(得分:0)

^(?=.*[a-zA-Z])[a-zA-Z0-9,_.&' -]+$

您可以通过lookahead强制执行条件,说明始终需要letter