Conditional validation on model in MVC

If you’re on MVC3/.NET4, you can use IValidatableObject which exists specifically for such purposes.

Quoting ScottGu,

…The IValidatableObject interface enables you to perform model-level
validation, and enables you to provide validation error messages
specific to the state of the overall model….

You model would look like

public class MyViewModel : IValidatableObject
    public long? Id { get; set; }
    public decimal? ProposedCost { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
        if (Id != null && ProposedCost == 0) {
            yield return new ValidationResult("ProposedCost must be provided.");

and then in the controller,

public ActionResult Submit(MyViewModel model)
    if (!ModelState.IsValid) {
        //failed - report an error, redirect to action etc
    //succeeded - save to database etc

Otherwise, the most clean solution would be to use view models – UpdateViewModel where the property is required, and CreateViewModel where it’s not required.

Leave a Comment