0

I need to be able to bypass/disable/change a view model's validation when inside other view model.

For example, this is my view model containing other view models:

public class OrderVM
{
    public SignMethod SignMethod { get; set; }
    public LoginVM LoginVM { get; set; }
    public RegisterVM RegisterVM { get; set; }
}
public class LoginVM
{
    [Required]
    public string Email { get; set; }

    // More properties here...
}
public class RegisterVM
{
    [Required]
    public string Email { get; set; }

    // More properties here...
}

And they have validation attributes (on the properties) that I would like to bypass/disable/change or add.

In this example, the view models of LoginVM and RegisterVM must contain required properties since it's a standalone view model for the login and register pages.

But, inside the OrderVM the required validation on LoginVM or RegisterVM should only be applied according to the SignMethod property, if the user has selected SignMethod.Login then the required validation on LoginVM should be applied and in RegisterVM should be disabled, and same for the opposite.

How can I achieve this behavior and represent it properly in the view models?

O. Shai
  • 703
  • 7
  • 22
  • Can you share your relevant code? Or you can refer to this article first, it may be helpful to you. https://www.pluralsight.com/guides/how-to-create-custom-attributes-csharp – Tupac Jun 15 '21 at 06:58
  • @NMSL - Yes, I have updated my question with my exact problem. I didn't find anything helpful in the article. The question should be more clear now. – O. Shai Jun 15 '21 at 09:30
  • 1
    You could use ModelState.Remove to remove a property to being validated.You can refer to this:https://stackoverflow.com/questions/49092199/how-can-i-modify-my-view-model-to-check-validation-for-only-specific-properties – Tupac Jun 25 '21 at 09:20
  • @NMSL - But how can I access it inside a validation attribute? and also does it remove a specific validation? – O. Shai Jun 26 '21 at 12:30

0 Answers0