要用于基于web的mvc3 .net应用程序,您会推荐哪种验证框架?应用程序遵循域模型模式,域模型POCOs在单独的类库中吗?
所需的验证类型将是...非Null、基于正则表达式等
发布于 2012-01-06 05:41:41
发布于 2012-01-06 06:40:47
如果您需要失败列表(而不是一次一个异常),那么我喜欢Enterprise Library Validation块。
查看powerpoint演示文稿,请访问:http://msdn.microsoft.com/en-us/library/ff650484.aspx
您可以针对您的POCO对象连接最基本的验证。许多预制规则可以在.config文件中设置。
你可以写你自己的规则。
我的规则非常细粒度。它们一次执行一个验证。
举个简单的例子:我有两个不同的规则来决定一个员工是否可以雇佣(基于生日)。其中一条规则是确保指定了员工的生日。
第二个规则将确保当前日期减去出生日期大于18年。(或者规则是什么)。
(现在让我们假设我有一堆规则)。因此,在验证例程运行之后,我得到了一个列表中的所有(无效)情况的列表。例如,如果我要验证一个员工,我会得到一个失效列表。
“未提供LastName”
“未提供FirstName”
“未提供SSN”
而不是“一次一个”。(“一次做一个”可能需要多次检查才能最终确定支票的有效性)。
下面是一些示例代码。假设有人想买一本ISBN为"ABC123456“的书。
下面是一个自定义规则,它将检查图书是否存在(例如,在您的产品数据库中)。我想你可以跟着去。它将与Book(.cs) poco对象绑定在一起。(没有显示任何"wire up“)。我只是想给你一个快速的例子,说明创建一个简单的规则有多难(或不难)。
当找不到一本书(使用isbn)....then时,您会看到validationResults.AddResult方法。这就是如何获得多个无效的。稍后在检查验证查询时,您将可以访问该集合。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
namespace MyCompany.Applications.MyApplication.BusinessLogic.Validation.MyType1Validations
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class BookExistsValidatorAttribute : ValidatorAttribute
{
protected override Validator DoCreateValidator(Type targetType)
{
return new BookExistsValidator("BookExistsValidatorTag");
}
}
public class BookExistsValidator : Validator<string>
{
public BookExistsValidator(string tag) : base("BookExistsValidatorMessageTemplate", tag) { }
protected override string DefaultMessageTemplate
{
get { throw new NotImplementedException(); }
}
protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
{
bool bookExists = BookMatchExists(objectToValidate);
if (!bookExists)
{
string msg = string.Format("The Book does not exist. Your ISBN='{0}'", objectToValidate);
validationResults.AddResult(new ValidationResult(msg, currentTarget, key, 10001, this)); /* 10001 is just some number I made up */
}
}
private bool BookMatchExists(string isbn)
{
bool returnValue = false;
IBookCollection coll = MyCompany.Applications.MyApplication.BusinessLogic.CachedControllers.BookController.FindAll(); /* Code not shown, but this would hit the db and return poco objects of books*/
IBook foundBook = (from item in coll where item.ISBN.Equals(book, StringComparison.OrdinalIgnoreCase) select item).SingleOrDefault();
if (null != foundBook)
{
returnValue = true;
}
return returnValue;
}
}
}https://stackoverflow.com/questions/8750208
复制相似问题