您的位置:首页 > 其它

自定义特性验证数据

2016-03-14 18:36 363 查看
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;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: