栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义模型验证

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义模型验证

创建一个类,引用 using System.ComponentModel.DataAnnotations;

    /// 
    /// 自定义模型验证
    /// 
    public class TestValidator
    {
        /// 
        /// 年龄大小验证
        /// 
        /// 
        /// 
        public static ValidationResult TestAge(int age)
        {
            if (age < 18)
            {
                return new ValidationResult("未满18岁");
            }
            else
            {
                return ValidationResult.Success;
            }
        }

        /// 
        /// 手机号码格式验证
        /// 
        /// 
        /// 
        public static ValidationResult TestPhone(string phone)
        {
            if ((phone.StartsWith("13") || phone.StartsWith("15") || phone.StartsWith("17")) && phone.Length == 11)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult("手机号码格式错误");
            }
        }
    }

需要验证的模型类

public class UserInfoToModel
    {
        [Required(ErrorMessage = "账号不能为空")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "密码不能为空"), MinLength(6, ErrorMessage = "密码不能小于6个字符")]
        public string UserPwd { get; set; }

        [CustomValidation(typeof(TestValidator), "TestAge")]
        public int UserAge { get; set; }

        [CustomValidation(typeof(TsetValidator), "TestPhone")]
        public string UserPhone { get; set; }
    }

[CustomValidation(typeof(类名),“方法名”)]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/314983.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号