FluentValidation: Check if one of two fields are empty

后端 未结 6 1108
醉话见心
醉话见心 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:55

    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:

    1. NotNull/NotEmpty
    2. Matches (regex)
    3. InclusiveBetween (range)
    4. CreditCard
    5. Email
    6. EqualTo (cross-property equality comparison)
    7. 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.

提交回复
热议问题