数据注解regulareexpression attribute with empty/null

本文关键字:empty null with attribute regulareexpression 数据 | 更新日期: 2023-09-27 18:15:07

我使用RegularExpressionAttribute来验证属性。该属性需要允许anything but zero length string, null, or (just) spaces。我使用的正则表达式是"^(?!^ *$)^.+$"

如果值是nullan empty string, RegularExpressionAttribute.IsValid总是返回真,但我相信它应该是假的(只是空格工作良好)。

我不是regex专家,但我相信表达式是ok的(如果我使用Regex.IsMatch直接从我的代码验证regex,空字符串返回false -如预期)。这是正则表达式属性的问题吗?

(我知道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 **

数据注解regulareexpression attribute with empty/null

令人沮丧的答案:尽管在RegEx中工作得很好,但在未能获得最简单的模式工作后,我确信在RegularExpressionAttribute中存在错误。事实证明,数据注释验证器简化了RegEx的实现,以防止新手错误。MSDN有这样的评论:

如果属性的值为null或空字符串("),则的值自动通过验证RegularExpressionAttribute属性。来验证值是否为如果不是null或空字符串,则使用RequiredAttribute属性。

所以从技术上讲不是一个bug——只是一个糟糕的想法。在我的情况下,修复是编写一个RegularExpressionAttribute扩展来处理null/empty's(我可以通过使用适当的正则表达式来验证RegularExpressionAttribute::IsValid。

不应该那么复杂。我不确定我理解完整的要求,但不只是"[^ ]"工作吗?