【问题标题】:Regex for 4 digits including 0 at first position not working right4位数字的正则表达式,包括第一个位置的0不能正常工作
【发布时间】:2020-04-14 19:48:30
【问题描述】:

我需要一个只允许 4 位数字的正则表达式,而这四个数字可以在任何位置包含 0。

下面是我的代码:

查看:

<label asp-for="UserId"></label><br />
<input asp-for="UserId" class="form-control" maxlength="4" />
<span asp-validation-for="UserId" class="text-danger"></span>

型号:

[RegularExpression(@"^([0-9]{4})$", ErrorMessage = "Please enter last 4 digits of your user Id.")]
[Display(Name = "Last 4 digits of user Id")]
public int? UserId{ get; set; }

但是如果我输入 0645,它会抛出一个错误“请输入您的用户 ID 的最后 4 位数字。”。如果我将其更改为 4567,它可以正常工作。那么我应该如何修复我的正则表达式?

【问题讨论】:

  • 它会抛出什么错误?
  • @Sweeper 它给出了我的错误信息;请输入您的用户 ID 的最后 4 位。
  • 它是否与@"^(\d{4})$" 引发了同样的错误?
  • 0645 被截断为 int 为 645 将其更改为字符串以保留 0... regex 不是问题,数据类型是。
  • 我相信问题不在于您的正则表达式,而在于您的输入字段。您将UserId 定义为int。这只会为您提供输入的数字表示。因此0123 在数字上只是123。如果您将输入字段类型更改为string,您应该没问题。

标签: c# regex asp.net-mvc asp.net-core


【解决方案1】:

您的正则表达式没有任何问题。正如 cmets 中已经说过的,您的属性是一个整数,当您在内部将其值设置为 0645 时,它会转换为 int 并变为 645。

如果您查看 GitHub 上的 RegularExpressionAttibute 类第 59 行,您会发现 IsValid 方法接收和对象,然后将其解析为字符串。


让我们看看你的数据的完整流程。

1) 您的用户在文本框中键入一个值。 ("0645")

2) ModelBinder 将输入的字符串转换为整数。 【645】

3) 在RegularExpressionAttibute.IsValid 内,您的整数再次转换为字符串(“645”)

4) 正则表达式应用于值 ("645") 而不是 ("0645")。所以它不会通过你的验证。

这是RegularExpressionAttibute.IsValid 方法。

override bool IsValid(object value) {
    this.SetupRegex();

    // Convert the value to a string
    string stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);

    // Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
    if (String.IsNullOrEmpty(stringValue)) {
        return true;
    }

    Match m = this.Regex.Match(stringValue);

    // We are looking for an exact match, not just a search hit. This matches what
    // the RegularExpressionValidator control does
    return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
} 

解决方案/建议是什么?

您期望 4 位数字作为输入,直到现在您还没有说必须对此进行任何类型的计算。

由于您不需要进行任何计算,因此您可以将其保存为字符串而不会造成任何伤害。只需继续验证您的字符串是否包含 4 位数字(您已经这样做了)。

如果您以后需要进行任何计算,只需在需要时将字符串转换为整数即可。

所以只要改变这一行:

public int? UserId{ get; set; }

到这里:

public string UserId{ get; set; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2011-12-04
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多