首页 > 解决方案 > 如何在 .NET Core 2 中的 [RegularExpression] 中使用变量?

问题描述

我正在开发一个需要使用其他正则表达式验证我的电子邮件输入字段的网络应用程序。

模型.cs ###

private string _regexOne = (@"myfirstregex")
private string _regexTwo = (@"mysecondregex");

public class InputModel
{
    [Required]
    [EmailAddress]
    [RegularExpression(((_regexOne)|(_regexTwo)), ErrorMessage = "My custom error message")] /* this line contains an error */
    [Display(Name = "Email")]
    public string Email { get; set; }

    ...
}

我需要多次使用这些正则表达式,所以我想全局声明它们,这样我就不必到处复制粘贴它们了。但是,上面的这段代码是错误的,无法运行。

所以我的问题是:我可以在这个属性中使用正则表达式的变量吗?如果是,语法是什么?

标签: c#.netregex

解决方案


将正则表达式定义为Constants可以使用的属性声明。请参见下面的示例:

using System;
using System.ComponentModel.DataAnnotations;

public class Program
{
    public const string Regex1 = "abc";
    public const string Regex2 = "xyz";
    public const string CompositeRegex = Regex1 + "|" + Regex2;

    public static void Main()
    {

        Console.WriteLine(Regex1);
        Console.WriteLine(Regex2);
        Console.WriteLine(CompositeRegex);      
    }
}

public class TestClass
{
    [RegularExpression(Program.Regex1  + "|" + Program.Regex2)]
    public string TestProperty {get; set;}
}

您可以编译并查看此代码

现场小提琴


推荐阅读