C# 正则表达式错误信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17296563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:04:22  来源:igfitidea点击:

Regular expression error message

c#asp.net-mvcvalidation

提问by John

Using the RegularExpression(@"^\d{1,15}$")], I want the user to enter digits up to 15 in length, which returns the error message 'Please enter up to 15 digits for a contact number'if this is not correct

使用RegularExpression(@"^\d{1,15}$")],我希望用户输入最长 15 位的数字,如果这不正确,则会返回错误消息“请输入最多 15 位的联系号码”

[Required(ErrorMessage = ("Please enter up to 15 digits for a contact number")), Display(Name = "Contact Number"), RegularExpression(@"^\d{1,15}$")]
public string ContactNumber { get; set; }

If the user fails to do this I am left with the error message:

如果用户未能做到这一点,我会留下错误消息:

The field Contact Number must match the regular expression '^\d{1,15}$'.

instead of 'Please enter up to 15 digits for a contact number'...does anyone know why? thanks

而不是'Please enter up to 15 digits for a contact number'......有谁知道为什么?谢谢

采纳答案by Darin Dimitrov

You have assigned the ErrorMessageto the RequiredAttribute(which you absolutely don't need in this case because of the regular expression). So:

您已将 the 分配ErrorMessage给 the RequiredAttribute(在这种情况下,由于正则表达式,您绝对不需要)。所以:

[Display(Name = "Contact Number")]
[RegularExpression(@"^\d{1,15}$", ErrorMessage = "Please enter up to 15 digits for a contact number")]
public string ContactNumber { get; set; }

回答by Jakub Konecki

You need to place your message in RegularExpressionattribute, not Requiredattribute.

您需要将消息放在RegularExpression属性中,而不是Required属性中。

You've added your error message to Requiredattribute, which means it will be displayed when the field is empty.

您已将错误消息添加到Required属性,这意味着它将在该字段为空时显示。