これは私のコードです:
RuleFor(x => x.Content).NotEmpty().Must(content => content.Trim().Length > 0);
次のように動作するはずです
if (NotEmpty(x.Content) && x.Content.Trim().Length > 0)
ステートメントですが、 isのNullReferenceException
場合にスローされます。x.Content
null
回避策を教えてください。
これは私のコードです:
RuleFor(x => x.Content).NotEmpty().Must(content => content.Trim().Length > 0);
次のように動作するはずです
if (NotEmpty(x.Content) && x.Content.Trim().Length > 0)
ステートメントですが、 isのNullReferenceException
場合にスローされます。x.Content
null
回避策を教えてください。
このコードも完全に機能するようです:
RuleFor(x => x.Content)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.Must(content => content.Trim().Length > 0);
Unless
条件に基づいてルールを実行できるものがあります。ただし、ルールを 2 つに分割する必要があります。
RuleFor(x => x.Content).NotEmpty();
RuleFor(x => x.Content).Must(content => content.Trim().Length > 0).Unless(x => x == null);
??
または、さらにコンパクトな演算子を使用することもできます。
RuleFor(x => (x.Content ?? "").Trim()).NotEmpty();
カスタム ルールを作成できます。ルールが true を返す場合は、ValidationFailure
. このようなもの:
public class ViewModelValidator : AbstractValidator<ViewModel>
{
public ViewModelValidator()
{
Custom(r => ContentIsEmpty(r) ? new ValidationFailure("Content", "Content must not be empty.") : null);
}
private static bool ContentIsEmpty(ViewModel viewModel)
{
return string.IsNullOrWhiteSpace(viewModel.Content);
}
}