200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > asp.net 利用特性和正则表达式进行字段的验证(attribute)

asp.net 利用特性和正则表达式进行字段的验证(attribute)

时间:2019-04-07 13:50:09

相关推荐

asp.net 利用特性和正则表达式进行字段的验证(attribute)

1.创建自定义的特性类(继承Attribute类)。

codingas below

[AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=false)]

public class FileVerification:Attribute

{

private string _regexStr;

public string RegexStr

{

get { return _regexStr; }

set { _regexStr = value; }

}

private string _showMessage;

public string ShowMessage

{

get { return _showMessage; }

set { _showMessage = value; }

}

}

2.在实体类属性上加上特性:

coding as below

public class Account

{

private string _user;

private string _password;

[FileVerification(RegexStr = @"^\w{1,50}$", ShowMessage = "请输入账号!")]

public string User

{

get { return _user; }

set { _user = value; }

}

[FileVerification(RegexStr = @"^\w{1,50}$", ShowMessage = "请输入密码!")]

public string Password

{

get { return _password; }

set { _password = value; }

}

}

3.利用正则表达式对属性的值进行验证通用类:

coding as below

public class FieldVerification<T>

{

public static string Verification(T t)

{

string returenMessage = "";

string fieldValue = "";

FileVerification fv = null;

Type customerType = typeof(T);

PropertyInfo[] pIList = customerType.GetProperties();

for (int i = 0; i < pIList.Length; i++)

{

object[] oList = pIList[i].GetCustomAttributes(typeof(FileVerification), true);

foreach (object o in oList)

{

fv = (FileVerification)o;

fieldValue = Convert.ToString(pIList[i].GetValue(t, null));

if (!Regex.IsMatch(fieldValue, fv.RegexStr))

{

returenMessage += fv.ShowMessage;

}

}

}

return returenMessage;

}

}

4.调用验证类:

coding as below

Account a = new Account();

a.User = "";

a.Password = "";

errorMessage = FieldVerification<Account>.Verification(a);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。