0

I have got two different models which extend an basemodel.

public class basemodel 
{
   public string prename;
   public string surname;
}

public class modelA : basemodel 
{
   public string street;
   public int gender; //0 = m / 1 = f
}

public class modelB : basemodel 
{
   public string street; 
}

Now I wanna validate them in my HTTP PUT controller. The controller decides between the modelA or modelB depending on the role a user has (admin can see modelA and user can see modelB).

public ActionResult Put(MyDto myDto)
{
   if (validationSrv.IsValid(myDto, ruleSetNames: "Edit", propertyNames: null))
   {
       session.Merge(myDto);
       session.Flush();
       session.Evict(myDto);
   } //else xyz
}

My actual validator looks like this.

public MyValidator() : AbstractValidator<basemodel>
{
   RuleSet("Edit", () =>
   {
       editBaseValidation();
   });
}

private void editBaseValidation()
{
   RuleFor(a => a.prename)
        .NotEmpty()
        .Length(5, 50);

   RuleFor(a => a.surname)
        .NotEmpty()
        .Length(5, 50);

   //say this is optional!
   RuleFor(a => a.street)
        .NotEmpty()

   //say this is optional!
   RuleFor(a => a.gender)
        .NotEmpty()
}

Now my question. Is there a way to say my validator that some attributes like street or gender are optional depending on the models used? So I can use only the validator for the basemodel and the validator decides which attribures to validate or not.

Thanks in advance :-)

1 Answer 1

0

I've found a solution to do this in another way. I'm using ASP.NET Core 2.1 so this is what I've found.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.