c# - Validator 未识别 RegularExpression 数据注释

标签 c# asp.net asp.net-mvc data-annotations

我相信代码是不言自明的。为什么 Validator 没有使用 RegularExpression 属性?

许可证.cs:

public class License {
  [Required]
  [RegularExpression("([0-9A-F]{4}\\-){4}[0-9A-F]{4}")]
  public string Code { get; set; }
}

LicenseTest.cs

[TestMethod]
public void TestValidationOfCodeProperty()
{
    // These tests pass so I know the regex is not the issue
    Assert.IsTrue(Regex.IsMatch("ABCD-EF01-2345-6789-FFFF", "([0-9A-F]{4}\\-){4}[0-9A-F]{4}"));
    Assert.IsFalse(Regex.IsMatch("abcd-ef01-2345-6789-ff00", "([0-9A-F]{4}\\-){4}[0-9A-F]{4}"));
    Assert.IsFalse(Regex.IsMatch("3331313336323034313135302020202020212121", "([0-9A-F]{4}\\-){4}[0-9A-F]{4}"));

    // Setup Validator
    License lic = new License();
    var ctx = new ValidationContext(lic);
    var results = new List<ValidationResult>();

    // Passes - TryValidateObject returns false because the required field is empty
    lic.Code = "";
    Assert.IsFalse(Validator.TryValidateObject(lic, ctx, results));

    // Passes - TryValidateObject returns true
    lic.Code = "10D0-4439-0002-9ED9-0743";
    Assert.IsTrue(Validator.TryValidateObject(lic, ctx, results));

    // FAILS - TryValidateObject returns true
    lic.Code = "3331313336323034313135302020202020212121";
    Assert.IsFalse(Validator.TryValidateObject(lic, ctx, results));
}      

最佳答案

使用 Validator.TryValidateObject(lic, ctx, results, true)

MSDN 解释了最后一个参数: https://msdn.microsoft.com/en-us/library/dd411772(v=vs.110).aspx

true to validate all properties; if false, only required attributes are validated

关于c# - Validator 未识别 RegularExpression 数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392809/

相关文章:

c# - 为什么在最内层的 for 循环中添加大括号会产生如此奇怪的结果?

c# - 跨AppDomain "Cancelable"事件

asp.net - 当主要内容需要时,如何在母版页上获取 'footer' 内容以向下推送?

asp.net-mvc - 从 cookie 问题中提取的自定义模型绑定(bind)器?

asp.net-mvc - ASP.NET MVC 升级指南

c# - Windows Phone 8.1 Silverlight 应用程序在调试器中启动并立即终止

c# - 从pkcs#11 token 或智能卡访问证书和私钥

asp.net - 如何在asp中填充图像和文本:Menu control

c# - 如何使 Web 应用程序项目独立于 IIS Express 和 SQL Server Express?

asp.net-mvc - Ninject 与 MembershipProvider |角色提供者