继上一个问题之后,我的nullable
课程中有一个名为char
的{{1}} source
。
Transaction
由于 //source isnt required but when present must be 1 character 'I' or 'M'
RuleFor(transaction => transaction.source.ToString())
.Matches("^[IM]?$")
.When(t => t.source.Value != null);
和Matches
不适用于When
,我使用char
方法,但是,如果生成新的.ToString()
对象,源属性为Transaction
,由于无法将null
来源转换为null
,应用程序失败。
如果来源不是string
,有人可以建议一种运行源 ONLY 验证的方法吗?我假设我编写的When表达式会执行此操作,如果source为null
,则会跳过验证过程的这一部分但是它会尝试处理验证的null
部分,因此导致错误。
答案 0 :(得分:3)
我不知道整个上下文,但我在这里看到一个最明显的解决方案:
RuleFor(transaction => transaction.source != null ? transaction.source.ToString() : string.Empty)
.Matches("^[IM]?$")
答案 1 :(得分:3)
Matches
和When
可用于char
数据类型。
我会建议像这样......
public class Transaction
{
public char? source { get; set; }
}
public class CustomerValidator : AbstractValidator<Transaction>
{
public CustomerValidator()
{
RuleFor(t => t.source)
.Must(IsValidSource);
}
private bool IsValidSource(char? source)
{
if (source == 'I' || source == 'M' || source == null)
return true;
return false;
}
}