我正在使用RegularExpressionAttribute
来验证属性。该属性需要允许anything but zero length string, null, or (just) spaces
。我使用的正则表达式是"^(?!^ *$)^.+$"
。
如果值是null
或an empty string
,则RegularExpressionAttribute.IsValid
始终返回true,但我认为它应该为false(空格可以正常工作)。
我不是正则表达式专家,但我相信表达式是可以的(如果我直接使用Regex.IsMatch
从我的代码验证正则表达式,则空字符串将返回false-如预期的那样)。这是RegularExpressionAttribute的问题吗?
(我知道RequiredAttribute通常是一种快速方法,但在这种情况下不是一种选择)
更新:
为了消除任何歧义,下面是一个简单的测试代码块来演示:
public class MyValueTester
{
// internal const string _REGEX_PATTERN = "^(?!\\s*$).+$";
// internal const string _REGEX_PATTERN = @"^(?!\s*$)";
internal const string _REGEX_PATTERN = @"[^ ]";
public MyValueTester()
{
ProperValue = "hello";
NullValue = null;
SpaceValue = " ";
LeadingSpaceValue = " hi";
EmptyValue = "";
}
[RegularExpression(_REGEX_PATTERN, ErrorMessage = "To err is human")]
public string ProperValue { get; set; }
[RegularExpression(_REGEX_PATTERN, ErrorMessage = "To null is human")]
public string NullValue { get; set; }
[RegularExpression(_REGEX_PATTERN, ErrorMessage = "To space is human")]
public string SpaceValue { get; set; }
[RegularExpression(_REGEX_PATTERN, ErrorMessage = "To empty is human")]
public string EmptyValue { get; set; }
[RegularExpression(_REGEX_PATTERN, ErrorMessage = "To lead is human")]
public string LeadingSpaceValue { get; set; }
}
测试代码:
MyValueTester myValueTester = new MyValueTester();
ValidationContext validationContext = new ValidationContext(myValueTester);
List<ValidationResult> validationResults = new List<ValidationResult>();
Debug.WriteLine("=== Testing pattern '" + MyValueTester._REGEX_PATTERN + "' ===");
var expectedResults = new[]
{
new {propertyName = "ProperValue", expectedPass = true},
new {propertyName = "LeadingSpaceValue", expectedPass = true},
new {propertyName = "NullValue", expectedPass = false},
new {propertyName = "SpaceValue", expectedPass = false},
new {propertyName = "EmptyValue", expectedPass = false},
};
bool isMatch = Validator.TryValidateObject(myValueTester, validationContext, validationResults, true);
foreach (var expectedResult in expectedResults)
{
ValidationResult validationResult = validationResults.FirstOrDefault(r => r.MemberNames.Contains(expectedResult.propertyName));
string result = expectedResult.expectedPass ? (validationResult == null ? "Ok" : "** Expected Pass **") : (validationResult != null ? "Ok" : "** Expected Failure **");
Debug.WriteLine("{0}: {1}", expectedResult.propertyName, result);
}
到目前为止的模式建议结果:
=== Testing pattern '^(?!\s*$).+$' ===
ProperValue: Ok
LeadingSpaceValue: Ok
NullValue: ** Expected Failure **
SpaceValue: Ok
EmptyValue: ** Expected Failure **
=== Testing pattern '^(?!\S*$)' ===
ProperValue: ** Expected Pass **
LeadingSpaceValue: ** Expected Pass **
NullValue: ** Expected Failure **
SpaceValue: Ok
EmptyValue: ** Expected Failure **
=== Testing pattern '^(?!\s*$)' ===
ProperValue: ** Expected Pass **
LeadingSpaceValue: ** Expected Pass **
NullValue: ** Expected Failure **
SpaceValue: Ok
EmptyValue: ** Expected Failure **
=== Testing pattern '[^ ]' ===
ProperValue: ** Expected Pass **
LeadingSpaceValue: ** Expected Pass **
NullValue: ** Expected Failure **
SpaceValue: Ok
EmptyValue: ** Expected Failure **
最佳答案
令人沮丧的答案:
我坚信尽管尽管在RegEx中可以正常工作,但未能使最简单的模式起作用后,RegularExpressionAttribute中还是存在错误。事实证明,数据注释验证器简化了RegEx的实现,以阻止新手错误。 MSDN有此评论:
如果属性的值为null或空字符串(“”),则
值自动通过验证
RegularExpressionAttribute属性。验证值是
不是null或空字符串,请使用RequiredAttribute属性。
因此从技术上讲不是错误-只是一个糟糕的主意。在我的情况下,解决方法是编写一个RegularExpressionAttribute扩展来处理空值/空值(我可以通过使用适当的正则表达式在RegularExpressionAttribute :: IsValid中进行验证来实现。