使用流畅验证在EITHER ... OR ...情况下允许空的验证规则

时间:2017-11-03 14:29:02

标签: asp.net asp.net-mvc validation nopcommerce fluentvalidation

如何为EITHER Email或PhoneNumber中的Allow Empty编写验证规则

RuleFor(x => x.Email).NotEmpty().WithMessage(localizationService.GetResource("ContactUs.Email.Required"));
RuleFor(x => x.PhoneNumber).NotEmpty().WithMessage(localizationService.GetResource("Products.MakeAnOffer.PhoneNumber"));

1 个答案:

答案 0 :(得分:3)

试试这个:

    RuleFor(x => x.Email)
        .NotEmpty()
        .When(x => string.IsNullOrEmpty(x.PhoneNumber))//will run only if PhoneNumber is empty
        .WithMessage(localizationService.GetResource("ContactUs.Email.Required"));

    RuleFor(x => x.PhoneNumber)
        .NotEmpty().When(x => string.IsNullOrEmpty(x.Email))//will run only if Email is empty
        .WithMessage(localizationService.GetResource("Products.MakeAnOffer.PhoneNumber"));