【问题标题】:Using .Matches with regex for a char in fluent使用 .Matches 和正则表达式获得流利的字符
【发布时间】:2014-04-14 09:45:55
【问题描述】:

我有一个名为 Transaction 的类,其中包含一个名为 source 的属性

Transaction 类中,我使用FluentValidation 进行了一些验证,我目前正在尝试使用regex 验证源属性,但是我遇到了问题

    //source isnt required but when present must be 1 character 'X' or 'Y'
    RuleFor(transaction => transacion.source)
        .Matches("^(X|Y)?$")
        .When(Transaction => transaction.source != null);

我得到:

错误 1 ​​FluentValidation.IRuleBuilderInitial&lt;MyUtility.Transaction,char?&gt; 不包含“匹配”的定义和最佳扩展 方法重载 FluentValidation.DefaultValidatorExtensions.Matches<T>(FluentValidation.IRuleBuilder<T,string>, System.Text.RegularExpressions.Regex) 有一些无效参数

我刚刚对不同的属性使用了完全相同的代码,没有任何问题,尽管那是一个字符串而不是一个字符。

【问题讨论】:

  • 不要认为这是你的问题,但仅供参考 (X|Y)[XY](搜索速度更快,可能更容易阅读)

标签: c# .net regex fluentvalidation


【解决方案1】:

在您的代码中Matches("^(X|Y)?$") 之间有一个额外的点.

.RuleFor(transaction => transaction.source)
    .Matches("^(X|Y)?$") // dot was here
    .When(transaction => transaction.source != null);

正如 Robin 指出的那样,正则表达式在 [XY] 格式中更具可读性。

编辑

我刚刚重读了您的帖子,它说source 属性是char,所以如果您将其转换为string,您将不会收到错误。

.RuleFor(transaction => transaction.source.HasValue ? transaction.source.ToString() : "")
    .Matches("^[XY]?$") // dot was here
    .When(transaction => transaction.source != null);

【讨论】:

  • 是的,我在发布后意识到了这一点,但是没有它仍然会收到相同的错误消息
  • @juan-facorro 正则表达式如何以 te [XY] 格式编写?
  • @SelectDistinct 刚刚用[XY] 格式编辑了答案。
  • @juan-facorro 如果源为空,则单元测试失败,这可能是,因为它是一个字符,因此在尝试转换为字符串时失败 - 有什么建议吗?
  • @SelectDistinct 解决方案非常简单。只需在 RuleFor 构造函数的 lambda 表达式中调用 .ToString() 之前测试 null.RuleFor(x =&gt; (x.source.HasValue ? x.source.ToString() : ""))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多