Reputation: 18630
I have a viewModel I want to perform some more custom validation on.
I have made my viewModel to inherit from IValidatable
and have some validation in:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
...
}
This works fine but I only want the validation for creates and not edits. I'm thinking the only way of doing this is some how determining within this method whether it is an edit or a create.
Is there a way of doing this or am I thinking aboout this whole thing incorrectly?
Upvotes: 1
Views: 514
Reputation: 10753
Use a separate view model for your create and insert actions. If your validation rules are that different, I think it would be worth it to use separate models anyway.
public class InsertMyObjectViewModel : IValidatable
{
[Required]
public string Name { get; set; }
// note the lack of Required attribute here
public string Address { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
...
}
}
And a separate for edit
public class UpdateMyObjectViewModel : IValidatable
{
[Required]
public string Name { get; set; }
[Required]
public string Address { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
...
}
}
This could make sense if your business rules dictate, for example, a customer's name upon registration but not their address. However, when a user modifies their account, your business rules may require an address. It makes sense in a lot of cases to use a 1:1 viewmodel:action ratio per object.
Now, when you write your Validate
logic, it becomes much simpler. There may be a bit of duplication, but it's easier to modify when your business rules change in the future.
Upvotes: 1