FluentValidation: Check if one of two fields are empty

后端 未结 6 1083
醉话见心
醉话见心 2020-12-24 05:26

I have this model

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName         


        
6条回答
  •  清酒与你
    2020-12-24 05:46

    Finally, this worked for me. I wanted to validate three properties where at least one is required. It returns an error message only once.

    RuleFor(p => p).Cascade(CascadeMode.StopOnFirstFailure)
                .Must(p => !string.IsNullOrWhiteSpace(p.FirstName))
                .When(p => p.Id == 0 && string.IsNullOrWhiteSpace(p.LastName)).WithMessage("At least one is required (Id, FirstName, LastName).")
                .Must(p => !string.IsNullOrWhiteSpace(p.LastName))
                .When(p => p.Id == 0 && string.IsNullOrWhiteSpace(p.FirstName)).WithMessage("At least one is required (Id, FirstName, LastName).")
                .Must(p => p.Id != 0)
                .When(p => string.IsNullOrWhiteSpace(p.FirstName) && string.IsNullOrWhiteSpace(p.LastName)).WithMessage("At least one is required (Id, FirstName, LastName).");
    

提交回复
热议问题