MVC validator for integer array in model

梦想与她 提交于 2019-12-11 22:17:43

问题


I have used validator required field in my model as follow and its working

  [Required(ErrorMessage = "Description is required.")]
        public string Description { get; set; }

Now i have another property of integer array type

 public string[] Roles { get; set; }

I am not able to get how can i put required field validator on integer array ?


回答1:


Write a custom validation attribute.

I've not tested but try code like this :

public class RequiredArray : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }
}

[RequiredArray (ErrorMessage = "Roles is required.")]
public string[] Roles{ get; set; }



回答2:


Personally i don't like using attributes for model validation,

You can use fluent validation http://fluentvalidation.codeplex.com/

So the validation logic is gathered at one place and doesn't pollute the model.



来源:https://stackoverflow.com/questions/19136006/mvc-validator-for-integer-array-in-model

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