Is it possible to toggle Validation Data Annotations on/off in MVC 3?

前端 未结 3 535
别跟我提以往
别跟我提以往 2021-01-13 20:36

I have two separate VIEWS accessing the same MODEL. When I put the validator data annotations on the model, it works as advertised and prevents the data from being submitte

3条回答
  •  醉梦人生
    2021-01-13 21:05

    This isn't possible via the default set of data annotations.. however, you have the choice of using 2 separate view models or writing your own validationAttribute.

    I wrote this once.. although I loathed using it..

    public class RequiredOnAttribute : ValidationAttribute
    {
        public string[] URLs { get; set; }
    
        public override bool IsValid(object value)
        {
            if (URLs.Contains(System.Web.HttpContext.Current.Request.Url.AbsolutePath))
            {
                if (string.IsNullOrEmpty(value as string))
                {
                    return false;
                }
            }
            return true;
        }
    }
    

    Usage:

    [RequiredOn(URLs = new string[] { "/create", "/edit" })]
    public string MyModelField { get; set; }
    

    You could do the same for Range, RegEx, etc..

提交回复
热议问题