ModelState validation checking multiple boolean property

我与影子孤独终老i 提交于 2019-12-12 20:35:36

问题


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;}
}

回答1:


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:

  1. Implements IValidateableObject
  2. 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!
        }
    }
}



回答2:


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; }
}


来源:https://stackoverflow.com/questions/24319014/modelstate-validation-checking-multiple-boolean-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!