I have view model that have multiple boolean properties, in my controller i have checking ModelState.IsValid
before proceeding to service layer. Now I want to make that ModelState.IsValid
return false
if none of boolean property set to true, is there a way to make it happen?
Here is my sample class
public class Role {
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;}
}
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!
}
}
}
You could extend ValidationAttribute:
public class MustBeCreatorEditorPublisherAttribute : ValidationAttribute
{
public NoJoeOnMondaysAttribute() { ErrorMessage = "You must be a creator, editor or publisher"; }
public override bool IsValid(object value)
{
using (Role role = value as Role)
{
return (role.IsCreator || role.IsEditor || role.IsPublisher);
}
return base.IsValid(value);
}
}
Your model:
[MustBeCreatorEditorPublisher]
public class Role
{
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; }
}