I would implement your own validation method on the model. Your model would end up looking something like this:
public class Role : IValidatableObject {
public int Id {get; set;}
[Required(ErrorMessage = "Please enter a role name")]
public string Name {get; set;}
public bool IsCreator {get; set;}
public bool IsEditor {get; set;}
public bool IsPublisher {get; set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (!this.IsCreator && !this.IsEditor && !this.IsPublisher)) {
yield return new ValidationResult("You must be a creator, editor or publisher");
}
}
}
Notice how the model:
- Implements
IValidateableObject
- Has a method named
Validate
which returns the type IEnumerable<ValidationResult>
During the model binding process this method will automatically be called and if a validation result is returned your ModelState
will no longer be valid. So using this familiar code in your controller will make sure you don't take any action unless your custom conditions check out:
public class SomeController {
public ActionResult SomeAction() {
if (ModelState.IsValid) {
//Do your stuff!
}
}
}