MVC 验证规则扩展(当RoleID 属性值为A,B 时,Email 属性必填)

public class RoleRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        public string  RoleIDS{ get; set; }

        public string OtherProperty { get; set; }

        public RoleRequiredAttribute(string  roleIDs, string otherProperty)
        {
            RoleIDS = roleIDs;
            OtherProperty = otherProperty;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectType.GetProperty(OtherProperty);
            if (property == null)
            {
                return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0} 不存在", OtherProperty));
            }
            var otherValue = property.GetValue(validationContext.ObjectInstance, null);
            if (RoleIDS.Replace("",",").Trim(',').Split(',').Contains(otherValue) && value == null)
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
         
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "role",
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
            };
            rule.ValidationParameters["property"] = Newtonsoft.Json.JsonConvert.SerializeObject(new { key = OtherProperty, val = RoleIDS });
             
            yield return rule;
        }
    }
(function ($) {    
$.validator.addMethod("role", function (value, element, param) {
        if (value.replace(/(^s*)|(s*$)/g, "").length != 0) {
            return true;
        }
        else {
            var obj = JSON.parse(param);
            var kv = $("#" + obj["key"]).val();
            if (obj["val"].indexOf(kv) != -1) {
                return false;
            }
            else {
                return true;
            }
        }
        return false;
    });
    $.validator.unobtrusive.adapters.addSingleVal("role", "property");

)(jQuery));
public class  MyModel
{

  [RoleRequired("A,B", "RoleID", ErrorMessage = "必填")]
   public string Email { get; set; }

   public string RoleID{ get; set; }
}
原文地址:https://www.cnblogs.com/valeb/p/7989401.html