• 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; }
    }
  • 相关阅读:
    git rebase 还是 merge的使用场景最通俗的解释
    漏洞复现:Struts2 远程代码执行漏洞(S2-033)
    linux临时网络配置
    漏洞复现:Struts2 S2-032 漏洞环境
    XXE攻击学习
    启用了不安全的HTTP方法【转】
    HTTP参数污染【转】
    逻辑漏洞挖掘方式
    大漏洞时代下的僵尸网络追踪-笔记
    markdown入门杂记
  • 原文地址:https://www.cnblogs.com/valeb/p/7989401.html
Copyright © 2020-2023  润新知