Validator 未识别 RegularExpression 数据注释
The RegularExpression data annotation is not being recognized by the Validator
我相信代码是不言自明的。为什么 RegularExpression
属性没有被 Validator
使用?
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));
}
使用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
我相信代码是不言自明的。为什么 RegularExpression
属性没有被 Validator
使用?
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));
}
使用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