博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#: Custom Validation Example
阅读量:6477 次
发布时间:2019-06-23

本文共 2021 字,大约阅读时间需要 6 分钟。

hot3.png

Validation is a big thing for any application.  I am currently working on implementing validation in my WCF layer that doesn't rely on me checking each operation and then hardcoding validation logic into a gigantic class.  I really like the way WCF does model validation, so I decided to start trying to reproduce it to figure out how they did it.
It turns out that it is pretty simple as the following code suggests.  I created a base attribute called Validation Attribute.  I created a BaseModel that has a validate method on it.  That method does some simple reflection to get all the attributes for all the properties in the given class.  It just calls IsValid on those attributes to run the specified logic. 
Check it out.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
publicclassBaseModel
{
    publicboolValidate()
    {
        var result =true;
 
        foreach(var propertyinthis.GetType().GetProperties())
        {
            foreach(var attributeinproperty.GetCustomAttributes(true))
            {
                if(attributeisValidationAttribute)
                {
                    try
                    {
                        var attr = (ValidationAttribute)attribute;
                        result = result && attr.IsValid(property.GetValue(this,null));
                    }
                    catch(Exception)
                    {
                        result =false;
                    }
                }
            }
        }
 
        returnresult;
    }
}
1
2
3
4
5
publicclassLoginModel : BaseModel
{
    [UserNameValidation]
    publicstringUserName {get;set; }
}
1
2
3
4
5
6
7
8
[System.AttributeUsage(System.AttributeTargets.Property)]
publicclassValidationAttribute : Attribute
{
    publicvirtualboolIsValid(objectobj)
    {
        returnfalse;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
publicclassUserNameValidationAttribute : ValidationAttribute
{
    privateconststringUSER_NAME_REGEX =@"^\w+$";
 
    publicoverrideboolIsValid(objectobj)
    {
        if(obj ==null)
        {
            returnfalse;
        }
 
        var value = objasstring;
         
        if(Regex.IsMatch(value, USER_NAME_REGEX))
        {
            returntrue;
        }
 
        returnfalse;
    }
}
1
2
3
4
5
6
7
8
9
classProgram
{
    staticvoidMain(string[] args)
    {
        var loginModel =newLoginModel();
        loginModel.UserName ="UserName";
        Console.WriteLine(loginModel.Validate());
    }
}

转载于:https://my.oschina.net/u/138995/blog/179065

你可能感兴趣的文章
Django templates加载css/js/image等静态资源
查看>>
Eclipse C + GTK2.0环境构筑
查看>>
caffe solver
查看>>
Rhel6-heartbeat+lvs配置文档
查看>>
[CF340D]Bubble Sort Graph/[JZOJ3485]独立集
查看>>
ORACLE分科目统计每科前三名的学生的语句
查看>>
第一次冲刺--查看活动详情用户场景分析
查看>>
0317复利计算的回顾与总结
查看>>
函数对象
查看>>
Sharepoint学习笔记—习题系列--70-573习题解析 -(Q70-Q72)
查看>>
最全最新个税计算公式---今天你税了吗?
查看>>
linux shell 正则表达式(BREs,EREs,PREs)差异比较(转,当作资料查)
查看>>
MongoDB--CSharp Driver Quickstart .
查看>>
#pragma mark 添加分割线 及 其它类似标记 - 转
查看>>
二分法求平方根(Python实现)
查看>>
使用startActivityForResult方法(转)
查看>>
so在genymotation中错误问题
查看>>
Visual Studio 原生开发的10个调试技巧(二)
查看>>
Windows内核再次出现0Day漏洞 影响win2000到win10所有版本 反病毒软件恐成瞎子
查看>>
H3C品牌刀片系统强势首发
查看>>