我有一个正则表达式,我试图找出我正在使用的 .NET 数据注释验证模型。目前它看起来像这样
[RegularExpression("^((?!City)[a-zA-Z '])+$", ErrorMessage = "City is required and must be properly formatted.")]
这个正则表达式的前半部分是为了说明城市,后半部分是为了确保它只有字母和空格。
输入文本框的默认值为City,所以只是“City”不能通过验证。我似乎无法让该正则表达式的第一部分让这些案例通过。
Cityville
City City
Jersey City
Arizona City
但这种情况没有通过:
City
任何帮助将不胜感激。
*编辑* 这个成功了:
^((?!^City$)[a-zA-Z '])+$
我更新了所有验证以包含此内容。以防万一你想看看我在做什么。如果我正在使用的整个验证数据模型的代码在这里。(使用正确的正则表达式更新)
public class FormModel {
[Required(ErrorMessage = "First Name is a Required field.")]
[DataType(DataType.Text)]
[Display(Order = 1, Name = "FirstName")]
[RegularExpression("^((?!^First Name$)[a-zA-Z '])+$", ErrorMessage = "First name is required and must be properly formatted.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is a Required field.")]
[DataType(DataType.Text)]
[Display(Order = 2, Name = "LastName")]
[RegularExpression("^((?!^Last Name$)[a-zA-Z '])+$", ErrorMessage = "Last name is required and must be properly formatted.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is a Required field.")]
[DataType(DataType.Text)]
[Display(Order = 3, Name = "Address")]
[RegularExpression("^((?!^Address$)[0-9A-Za-z #.,])+$", ErrorMessage = "Address is required and must be properly formatted.")]
public string Address { get; set; }
[DataType(DataType.Text)]
[Display(Order = 4, Name = "Address2")]
public string Address2 { get; set; }
[Required(ErrorMessage = "City is a Required field.")]
[DataType(DataType.Text)]
[RegularExpression("^((?!^City$)[a-zA-Z '])+$", ErrorMessage = "City is required and must be properly formatted.")]
[Display(Order = 6, Name = "City")]
public string City { get; set; }
[Required( ErrorMessage = "State is a Required field." )]
[DataType( DataType.Text )]
[Display( Order = 7, Name = "State" )]
public IEnumerable<String> State { get; set; }
[Required( ErrorMessage = "Zip is a Required field." )]
[DataType( DataType.Text )]
[RegularExpression( "\\d{5}",
ErrorMessage = "Zip Code is required and must be properly formatted.")]
[Display( Order = 8, Name = "Zip" )]
public String Zip { get; set; }
[Required( ErrorMessage = "Phone is a Required field." )]
[DataType( DataType.PhoneNumber )]
[RegularExpression( "^[01]?[- .]?\\(?[2-9]\\d{2}\\)?[- .]?\\d{3}[- .]?\\d{4}$",
ErrorMessage = "Phone is required and must be properly formatted.")]
[Display( Order = 9, Name = "Phone" )]
public string Phone { get; set; }
[Required( ErrorMessage = "Email is a Required field." )]
[DataType( DataType.EmailAddress )]
[RegularExpression( "^[A-Za-z0-9._%+-]*@[A-Za-z0-9.-]*\\.[A-Za-z0-9-]{2,}$",
ErrorMessage = "Email is required and must be properly formatted.")]
[Display( Order = 10, Name = "Email" )]
public string Email { get; set; }