C# 验证程序无法识别RegularExpression数据批注
我相信这段代码是不言自明的。为什么C# 验证程序无法识别RegularExpression数据批注,c#,asp.net,asp.net-mvc,data-annotations,C#,Asp.net,Asp.net Mvc,Data Annotations,我相信这段代码是不言自明的。为什么验证器不使用RegularExpression属性 License.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 TestValidationOfCodePrope
验证器不使用RegularExpression
属性
License.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));
}
[TestMethod]
public void TestValidationOfCodeProperty()
{
//这些测试通过了,所以我知道正则表达式不是问题所在
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(“333131333632303431353020202022121”),“([0-9A-F]{4}\\-){4}[0-9A-F]{4}”);
//设置验证器
许可证lic=新许可证();
var ctx=新的ValidationContext(lic);
var results=新列表();
//passs-TryValidateObject返回false,因为必填字段为空
lic.Code=“”;
IsFalse(Validator.TryValidateObject(lic、ctx、results));
//passs-TryValidateObject返回true
lic.Code=“10D0-4439-0002-9ED9-0743”;
IsTrue(Validator.TryValidateObject(lic、ctx、results));
//失败-TryValidateObject返回true
lic.Code=“3331313336323034313530202022121”;
IsFalse(Validator.TryValidateObject(lic、ctx、results));
}
使用验证程序.TryValidateObject(lic、ctx、results、true)
MSDN解释了最后一个参数:
true以验证所有属性;如果为false,则仅需要属性
已验证