多个单独的正则表达式 [英] Multiple Separate Regular Expressions

查看:75
本文介绍了多个单独的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序.此应用程序包含一个表格,我需要对其进行多次正则表达式检查,具体取决于问题,该表格应具有不同的错误.

I have an ASP.NET MVC application. This application contains a form for which I need to make multiple regular expression checks, which should have different errors depending on the issue.

有人知道我要如何处理单独的错误吗?我尝试在一个模型属性上使用多个RegularExpression批注,但这会在编译时引发错误.这是代码示例:

Does anyone know the way in which I would go about having separate errors? I have tried using multiple RegularExpression annotations on one model property, but this throws an error upon compilation. Here is a sample of the code:

[Required]
[Display(Name = "Distribution List Name")]
[StringLength(65, ErrorMessage = "Must be under 65 characters")]
[RegularExpression("^#(CONTOSO|MEGACORP|TESTCOMPANY)([-_A-Za-z0-9 ]+)$", ErrorMessage = "Invalid company, or the name contains invalid characters (Allowed characters are alphanumeric, - and _)")]
public string Name { get; set; }

理想情况下,我希望在字符串开头检查公司,并允许进行字符检查以抛出单独的错误消息.

Ideally, I would like the check for the company at the start of the string, and the allowed character check to throw separate error messages.

推荐答案

您可以考虑的2个选项

a.创建一个自定义属性,使其可以多次应用(使用AllowMultiple=true).

a. Create a custom attribute that allows it to be applied multiple times (using AllowMultiple=true).

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=true)]
public class MyAttribute: RegularExpressionAttribute
{
  ....
}

并将其注册到Global.asax.cs

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyAttribute), typeof(RegularExpressionAttributeAdapter));

请注意,我尚未测试此方法是否可以与客户端验证一起使用

Note, I haven't tested if this works with client side validation

b.创建一个自定义验证器并分别测试每个正则表达式并返回相应的消息.

b. Create a custom validator and test each regex separately and return the appropriate message.

public class MyAttribute : ValidationAttribute, IClientValidatable
{
  ....
}

这篇关于多个单独的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆