asp.net mvc 的属性属性中的正则表达式

问题描述 投票:0回答:1

我想防止用户名中出现空格和特殊字符,但我不知道如何在一个数据属性中做到这一点,并且 asp.net mvc 只允许每个属性有 1 个正则表达式属性。

    [Required()]
    [StringLength(10, MinimumLength = 6, ErrorMessage = "Min 6 and max 10 characters")]
    [Display(Name = "User Name")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")]
    [RegularExpression(@"^[\%\/\\\&\?\,\'\;\:\!\-]+$", ErrorMessage = "No special characters")]
    [Remote("IsUsernameDuplicate", "Account", HttpMethod = "Get", ErrorMessage = "The username is already in use")]
    public string UserName { get; set; }

编辑1 我已将属性更改为

    [Required()]
    [MinLength(5, ErrorMessage = "Minimum length is 5")]
    [MaxLength(12, ErrorMessage = "Maximum length is 12")]
    [Display(Name = "User Name")]
    [RegularExpression(@"^[A-Za-z0-9_]$", ErrorMessage = "Hey, no funny symbol stuff")]
    [Remote("IsUsernameDuplicate", "Account", HttpMethod = "Get", ErrorMessage = "The username is already in use")]
    public string UserName { get; set; }

但是我在输入 Chuck 并按 Tab 时遇到错误

enter image description here

regex asp.net-mvc custom-data-attribute
1个回答
0
投票

带有

A-Za-z0-9
并且仅允许
_
的用户名正则表达式(像大多数用户名一样)将是:

^[A-Za-z0-9_]{5,12}$

既然检查了最小和最大长度,您可以使用

^[A-Za-z0-9_]+$

Regex101 演示

© www.soinside.com 2019 - 2024. All rights reserved.