Hiteshkumar Vaghasiya
Hiteshkumar Vaghasiya

Reputation: 432

Validation rule for Allow Empty in EITHER ... OR ... case using fluent validation

How to write a Validation rule for Allow Empty in EITHER Email OR in PhoneNumber

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

Upvotes: 0

Views: 2216

Answers (1)

Roman Koliada
Roman Koliada

Reputation: 5122

Try this:

    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"));

Upvotes: 5

Related Questions