自定義特性驗證數據

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ValidateConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("----------------------------------------");


            var u = new User { Name = "jinshuaijinshuaijinshuaijinshuaijinshuai", Age = 0 };


            var result=   ValidateCore.Validte<User>(u);


            foreach (var r in result)
            {

                Console.WriteLine(r);

            }




            Console.WriteLine("----------------------------------------");

            Console.Read();
        }
    }




    public class User
    {

        [RegexValidate(ErrorMessage = "用戶名信息太長或過短!", Regex = "^\\w{5,10}$")]
        [RegexValidate(ErrorMessage="用戶名必須以s開頭!",Regex="^s\\w+$")]
        public string Name { get; set; }

        [RegexValidate(ErrorMessage = "年齡輸入錯誤!", Regex = "^[1-9]{1,3}$")]
        public int Age { get; set; }

    }



    public interface IValidate 
    {
        string ErrorMessage { get; set; }

        bool Validate<T>(T para);

        string Regex { get; set; }
    }





    [AttributeUsage(AttributeTargets.Property,AllowMultiple=true, Inherited = false)]
    [Serializable]
    public class RegexValidate : Attribute, IValidate
    {
        public string ErrorMessage { get; set; }

        public bool Validate<T>(T para)
        {
            var value = para.ToString();

            var r = new Regex(Regex);
            return r.IsMatch(value);
        }

        public string Regex { get; set; }
    }






    public class ValidateCore
    {
        public static List<string> Validte<T>(T model) where T:class
        {
            var errorMessage = new List<string>();

            var t = model.GetType();

            var p = t.GetProperties();

            foreach (var c in p)
            {
                var a = c.GetCustomAttributes(typeof(IValidate), true);

                foreach (var b in a)
                {
                    var d = b as IValidate;

                    if (d == null)
                    {
                        continue;
                    }


                    bool v = d.Validate(c.GetValue(model, null));


                    if (!v)
                    {
                        errorMessage.Add(d.ErrorMessage);
                    }
                }
            }

            return errorMessage;

        }

    }

}
相關文章
相關標籤/搜索