'FluentValidation: How to show client-side validation

I am using FluentValidation

public class AddressModel{
  public string Street{get; set;}
  public string City{get; set;}
  public string State{get; set;}
  public string Zip{get; set;}
  public string Country{get; set;}
}

public class PersonModel{
  public string FirstName {get; set;}
  public string LastName {get; set;}
  public string SSN {get; set;}
  public AddressModel Address{get; set;}
  public AddressModel MailingAddress{get; set;}
  public int Type {get; set;}
}

 public class AddressValidator : AbstractValidator<AddressModel>
{
  public AddressValidator()
  {
    RuleFor(p=>p.Street).NotEmpty().WithMessage("Street is required");
    RuleFor(p=>p.City).NotEmpty().WithMessage("City is required");
    RuleFor(p=>p.Country).NotEmpty().WithMessage("Country is required");
    RuleFor(p=>p.State).NotEmpty().WithMessage("State is required"); 
    RuleFor(p=>p.Zip).NotEmpty().WithMessage("Zip code is required")
  }
}

public class PersonValidator : AbstractValidator<PersonModel>
{
  public PersonValidator()
  {
    RuleFor(p=>p.FirstName).NotEmpty().WithMessage("First name is required");
    RuleFor(p=>p.LastName).NotEmpty().WithMessage("Last name is required");
    RuleFor(p=>p.Address).SetValidator(new AddressValidator());
    RuleFor(p=>p.SSN).NotEmpty().WithMessage("SSN is required").When(p=>p.Type ==1); 
  }
}

//Startup

services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .AddFluentValidation(fv =>
          {
             fv.RegisterValidatorsFromAssemblyContaining<Startup>();
          });

When I click Save on the UI, I will get following required fields: FirstName, LastName and Address. After I fill all marked required fields and click again Save, I will get from server that MailingAddress and SSN is required (I selected type = 1).

What do I need to do so I do not have validation for MailingAddress? Is it possible to have SSN validation available on the client-side?

Thank you for your help



Solution 1:[1]

SSN client side: I suspect you'd need to write a custom client side adapter. The out of the box client side support is quite limited and it's probably not firing because of your additional When clause.

I used this as a guide when I had to build my own.

MainAddress server side: is this being populated in your model before invoking the server side validation? Or is it null? With no explicit rule defined I would have expected the validator to ignore it. There is a Null() rule that can be applied to a property to ensure it is null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rgvlee