gpt4 book ai didi

c# - 带空/空的数据注释 RegularExpressionAttribute

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:39 24 4
gpt4 key购买 nike

我正在使用 RegularExpressionAttribute 来验证属性。该属性需要允许除零长度字符串、null 或(仅)空格之外的任何内容。我使用的正则表达式是 "^(?!^ *$)^.+$".

如果值为 null空字符串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 has this comment :

If the value of the property is null or an empty string (""), thevalue automatically passes validation for theRegularExpressionAttribute attribute. To validate that the value isnot null or an empty string, use the RequiredAttribute attribute.

所以从技术上讲不是错误 - 只是一个糟糕的主意。在我的例子中,解决方法是编写一个 RegularExpressionAttribute 扩展来处理空值/空(我可以通过使用适当的正则表达式在 RegularExpressionAttribute::IsValid 中验证来做到这一点。

关于c# - 带空/空的数据注释 RegularExpressionAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com