【问题标题】:mvc data annotation to restrict user to not allow only numeric numbers and special charactersmvc 数据注释以限制用户只允许数字和特殊字符
【发布时间】:2026-01-26 07:26:01
【问题描述】:

我正在尝试验证用户的输入是否仅插入字母数字字符,包括特殊字符,如 .,_ 空格。

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

【问题讨论】:

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


    【解决方案1】:

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

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

    DEMO

    • (?![\W_]+$) Negative lookahead 断言字符串不会只包含特殊字符。

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

    【讨论】:

    • 谢谢你的回答,很好。但它不允许我使用逗号和下划线,你能解决这个问题吗?
    • 您可以将上述正则表达式简化为@"^(?![\W_]+$)(?!\d+$)[\w .&amp;',-]+$"
    【解决方案2】:
    ^(?=.*[a-zA-Z])[a-zA-Z0-9,_.&' -]+$
    

    您可以通过lookahead 强制执行一个条件,说明letter 始终是必需的。

    【讨论】: