While working through the MVC 2 NerdDinner tutorial I see that some business logic (required fields, maximum lengths, etc.) can be added to individual properties on the model.
How do you add more complex validation rules? For example, requiring exactly one of two properties to be populated?
Example [QuantumMechanics/Models/Particle.cs]:
namespace QuantumMechanics.Models
{
[MetadataType(typeof(Particle_Validation))]
public partial class Particle {
}
public class Particle_Validation
{
// Mass is required; easy enough.
[Required(ErrorMessage="Mass is required.")]
public Mass double {get; set; }
// How do I require exactly one or the other?
public Position double {get; set; }
public Momentum double {get; set; }
}
}
Thought I’d post the solution I went with. Like Spencerooni said, there is not an elegant mechanism to add complex validation to the model itself, but this seems to work. It leverages the DefaultModelBinder interface’s OnModelUpdated method override to invalidate the underlying model anytime it is updated.
Note that DataAnnotations on a Model’s properties are only invoked when a bound field is posted back, which means validation will pass on a form without a field for Mass at all.
Global.asax
Models/ParticleModelBinder.cs