zoukankan      html  css  js  c++  java
  • 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; }
    }
  • 相关阅读:
    yum error
    Linux如何查询内存真实利用率
    管理工作
    top 详解
    炒股
    vsftp+apache中文乱码问题
    生活像杯咖啡
    vmware workstation 9 nat setting
    cp文件
    WPF 数据分页控件改进
  • 原文地址:https://www.cnblogs.com/valeb/p/7989401.html
Copyright © 2011-2022 走看看