zoukankan      html  css  js  c++  java
  • Asp.Net Core 自定义验证属性

      很多时候,在模型上的验证需要自己定义一些特定于我们需求的验证属性。所以这一篇我们就来介绍一下怎么自定义验证属性。

      我们来实现一个验证邮箱域名的自定义验证属性,当然,最重要的是需要定义一个继承自ValidationAttribute的类,然后在实现其IsValid方法。

    public class ValidEmailDomainAttribute : ValidationAttribute
    {
        private readonly string allowedDomain;
    
        public ValidEmailDomainAttribute(string allowedDomain)
        {
            this.allowedDomain = allowedDomain;
        }
    
        public override bool IsValid(object value)
        {
            string[] strings = value.ToString().Split('@');
            return strings[1].ToUpper() == allowedDomain.ToUpper();
        }
    }

      然后就可以在我们的Model上面使用  ValidEmailDomain 属性来校验,如下:

    public class RegisterViewModel
    {
    
        [Required]
        [Display(Name = "邮箱地址")]
        [EmailAddress]
        [Remote(action: "IsEmailInUse", controller: "Account")]
        [ValidEmailDomain(allowedDomain: "qq.com",
        ErrorMessage = "电子邮件的后缀必须是qq.com")]
        public string Email { get; set; }
    
        [Required]
        [Display(Name = "密码")]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    
        [DataType(DataType.Password)]
        [Display(Name = "确认密码")]
        [Compare("Password",
            ErrorMessage = "密码与确认密码不一致,请重新输入.")]
        public string ConfirmPassword { get; set; }
    
        public string City { get; set; }
    }
  • 相关阅读:
    关于返回上一页功能
    Mybatis Update statement Date null
    SQLite reset password
    Bootstrap Validator使用特性,动态(Dynamic)添加的input的验证问题
    Eclipse使用Maven2的一次环境清理记录
    Server Tomcat v7.0 Server at localhost failed to start
    PowerShell一例
    Server Tomcat v7.0 Server at libra failed to start
    商标注册英语
    A glance for agile method
  • 原文地址:https://www.cnblogs.com/jesen1315/p/11561830.html
Copyright © 2011-2022 走看看