如何使用 DataAnnotations & Regex - c# - ASP.NET Core
Posted
技术标签:
【中文标题】如何使用 DataAnnotations & Regex - c# - ASP.NET Core【英文标题】:How to use DataAnnotations & Regex - c# - ASP.NET Core 【发布时间】:2021-03-17 16:11:58 【问题描述】:我正在使用数据注释来匹配用户为错误处理目的而输入的字段。
每当他们输入不正确的格式时,它就会打印实际的正则表达式,我想知道是否有办法删除“匹配以下正则表达式”并只打印错误消息。
我的表单示例和显示的错误消息: Form
我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace FoodCart.Models
public class Order
public int ID get; set;
[Display(Name = "First Name")]
[RegularExpression(@"^[a-zA-Z''-'\s]1,40$")]
[Required(ErrorMessage = "This field is required")]
public string FirstName get; set;
[Display(Name = "Last Name")]
[RegularExpression(@"^[a-zA-Z''-'\s]1,40$")]
[Required(ErrorMessage = "This field is required")]
public string LastName get; set;
[Required(ErrorMessage = "This field is required")]
public string Address get; set;
[Required(ErrorMessage = "This field is required")]
public string City get; set;
[Required(ErrorMessage = "This field is required")]
public string State get; set;
[Required(ErrorMessage = "This field is required")]
public string Zip get; set;
[Display(Name = "Name on Card")]
[Required(ErrorMessage = "This field is required")]
public string NameonCard get; set;
[Display(Name = "Credit Card Number")]
[Required(ErrorMessage = "This field is required, input valid 16 digit number")]
[RegularExpression(@" ([0 - 9][0 - 9][0 - 9][0 - 9]) ([0 - 9][0 - 9][0 - 9][0 - 9]) ([0 - 9][0 - 9][0 - 9][0 - 9]) ([0 - 9][0 - 9][0 - 9][0 - 9])")]
public string CreditCardNum get; set;
[Display(Name = "Expiration Date")]
[Required(ErrorMessage = "This field is required, input valid expiration date: MM/YY")]
[RegularExpression(@"([0-9][0-9])\/([0-9][0-9])")]
public string ExpDate get; set;
[Display(Name = "CVV")]
[RegularExpression(@"([0-9][0-9][0-9])")]
[Required(ErrorMessage = "This field is required")]
public string cvv get; set;
[Display(Name = "Total")]
public decimal YourTotal get; set;
public int UserLinkID get; set;
【问题讨论】:
您选择的模式不合适。你想用这个模式做什么? 【参考方案1】:验证属性都带有内置在实现中的默认错误消息。对于RegularExpressionAttribute
,此错误消息如下:
字段 0 必须匹配正则表达式“1”。
占位符 0
将是正在验证的属性的显示名称,1
将是正则表达式本身。
有几种方法可以自定义此错误消息,使用properties on the validation attribute 之一。最简单的方法是直接使用 ErrorMessage
属性指定错误消息。请注意,如果您愿意,您仍然可以参考占位符 0
(用于字段名称)和 1
(用于正则表达式):
[Display(Name = "First Name")]
[RegularExpression(@"^[a-zA-Z'-\s]1,40$", ErrorMessage = "The field 0 is not a valid name")]
public string FirstName get; set;
【讨论】:
【参考方案2】:[RegularExpression(@"([0-9][0-9])\/([0-9][0-9])",ErrorMessage = "your message")]
【讨论】:
以上是关于如何使用 DataAnnotations & Regex - c# - ASP.NET Core的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 DataAnnotations 处理 ASP.NET MVC 2 中的布尔值/复选框?
.NET 4.0 DataAnnotations GAC/EntityFramework 冲突
如何覆盖DataAnnotations必需标记以允许条件客户端验证