1
votes

is there a way to use conditional validation on MVC3 model?

for example:

public class User
{ 
    [Required]
    public string Password { get; set; } 
    [Required, Compare("Password")] 
    public string ComparePassword { get; set; } 
}

Where i would like Password and confirmpassword fields to be required ONLY when adding a new user. However when editing I would like these to be empty (text boxes in the view). Only when user does type in a new Password and ConfirmPassword will the password be changed in the DB.

Thanks

1

1 Answers

2
votes

Typically you would have separate AddUserViewModel and EditUserViewModel classes with the appropriate fields and validators. Then in your controller action if the model is valid, you convert to your view models to your User entity and pass it on to your business logic / service to save. You can use Automapper for this.