FluentValidation: Check if one of two fields are empty
Try this
RuleFor(person => person).Must(person => !string.IsNullOrEmpty(person.FirstName) || !string.IsNullOrEmpty(person.LastName))
I did like this to check charges entered are same to previous one or not. If charges are same as previous one than it'll give an error. This worked for me.
public class CasualMealChargeValidator : AbstractValidator<CasualMealCharge>
{
public CasualMealChargeValidator(CasualMealCharge CMC)
{
//RuleFor(x => x.BankName).NotEmpty().When(pm => pm.PaymentMode == "Cheque").WithMessage("Enter Bank.");
RuleFor(x => x).Must(x => x.DN != CMC.DN || x.BF != CMC.BF || x.LN != CMC.LN).WithMessage("Not Saved - Meal charges are same as current charges.").WithName("CMFor");
}
}
You can use When/Unless condition:
RuleFor(m => m.FirstName).NotEmpty().When(m => string.IsNullOrEmpty(m.LastName));
RuleFor(m => m.LastName).NotEmpty().When(m => string.IsNullOrEmpty(m.FirstName));
or
RuleFor(m => m.FirstName).NotEmpty().Unless(m => !string.IsNullOrEmpty(m.LastName));
RuleFor(m => m.LastName).NotEmpty().Unless(m => !string.IsNullOrEmpty(m.FirstName));
As for your second question, FluentValidation
works with client-side validation, but not all rules are supported. Here you can find validators, that are supported on the client-side:
- NotNull/NotEmpty
- Matches (regex)
- InclusiveBetween (range)
- CreditCard
- EqualTo (cross-property equality comparison)
- Length
For rules that are not in the list you have to write your own FluentValidationPropertyValidator
and implement GetClientValidationRules
. You can find a few samples of this on the StackOverflow by doing simple search.