EnterpriseLibrary数据验证(一)编程方式进行验证

class Program
    {
        static void Main(string[] args)
        {
            //验证1

            Validator<School> tmp1 = ValidationFactory.CreateValidator<School>();
            School tmpSchool = new School(null);
            //注意:Validate有验证顺序的,顺序按照属性的排列顺序
            ValidationResults v = tmp1.Validate(tmpSchool);
            Console.WriteLine("验证结果:{0}", v.IsValid);
            tmpSchool.SchoolName = "aaaaa";

            //这句是在验证SchoolAddress属性
            ValidationResults vv = tmp1.Validate(tmpSchool);
            Console.WriteLine("验证结果:{0}", vv.IsValid);

            tmpSchool.SchoolAddress = "aaa";
            //这句验证SchoolName
            ValidationResults vvv = tmp1.Validate(tmpSchool);
            Console.WriteLine("验证结果:{0}", vvv.IsValid);

            DateTime dt = new DateTime(2011, 12, 2);
            Validator<DateTime> v1 = new DateTimeRangeValidator(DateTime.Parse("2011-1-1"), DateTime.Parse("2011-11-11"));
            ValidationResults v2 = v1.Validate(dt);
            Console.WriteLine("验证结果:{0}", v2.IsValid);

            RangeValidator tmp = new RangeValidator(1, 10);
            int k = 5;
            ValidationResults v3 = tmp.Validate(k);
            Console.WriteLine("验证结果:{0}", v3.IsValid);

            //Exclusive:<不包括等于  Inclusive<=包括等于 Ignore排除这部分范围
            RangeChecker<int> v4 = new RangeChecker<int>(1, RangeBoundaryType.Ignore, 10, RangeBoundaryType.Inclusive);
            int j = 10;
            Console.WriteLine("验证结果:{0}", v4.IsInRange(j));
            Console.ReadKey();
        }
    }

 

    public class School
    {
        private string _SchoolName;

        //组合验证,使用与方式;注意:只对属性进行验证,私有成员是验证不了的
        [ValidatorComposition(CompositionType.And)]
        [StringLengthValidator(5)]
        [NotNullValidator]
        public string SchoolName
        {
            get { return _SchoolName; }
            set { _SchoolName = value; }
        }

        public School(string a)
        {
            SchoolName = a;
        }

        private string _SchoolAddress;

        //组合验证,使用或方式
        [ValidatorComposition(CompositionType.Or)]
        [NotNullValidator]
        [StringLengthValidator(5)]
        public string SchoolAddress
        {
            get { return _SchoolAddress; }
            set { _SchoolAddress = value; }
        }
    }

 

此方式不必要在CONFIG文件中配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值