c# - 如何在 .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; }
...
}
我需要多次使用这些正则表达式,所以我想全局声明它们,这样我就不必到处复制粘贴它们了。但是,上面的这段代码是错误的,无法运行。
所以我的问题是:我可以在这个属性中使用正则表达式的变量吗?如果是,语法是什么?
解决方案
将正则表达式定义为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;}
}
您可以编译并查看此代码
推荐阅读
- c# - 使用 EWS 托管 API 将 .msg 文件上传到 Exchange Server
- arrays - 带有 *ngFor 的 JSON 对象循环(Angular 5)
- php - 如何解决 Wordpress 404 错误页面中的致命错误?
- javascript - 调用导入类的方法时使用 Async/Await
- sql - 嵌套 XML 输出
- html - Angular 6 - 在 mat-select 上动态设置 [必需]
- asp.net-mvc - 模型的类属性的属性不具有约束力
- botframework - 自动化微软机器人测试
- docker - 同一个 docker 端口可以用于两个不同的应用程序吗?
- ibm-mq - 我们可以用其他用户重命名 MUSR_MQADMIN