首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >4位数的正则表达式,包括第一个位置的0不能正常工作

问4位数的正则表达式,包括第一个位置的0不能正常工作
EN

Stack Overflow用户
提问于 2019-12-23 22:09:32
回答 1查看 405关注 0票数 2

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

下面是我的代码:

查看:

代码语言:javascript
复制
<label asp-for="UserId"></label><br />
<input asp-for="UserId" class="form-control" maxlength="4" />
<span asp-validation-for="UserId" class="text-danger"></span>

型号:

代码语言:javascript
复制
[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位数字。”.If我把它改成4567,它工作得很好。那么我应该如何修复我的正则表达式呢?

EN

回答 1

Stack Overflow用户

发布于 2019-12-25 03:59:33

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

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

因此,让我们看看您的数据流的完整流程。

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

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

3)在RegularExpressionAttibute.IsValid中,整数再次转换为字符串("645")

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

这是RegularExpressionAttibute.IsValid方法。

代码语言:javascript
复制
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; }

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59456726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档