要用于基于web的mvc3 .net应用程序,您会推荐哪个验证框架? 应用程序遵循领域模型模式,领域模型POCO在单独的类库中?
需要的验证类型将是...非空、基于正则表达式等。
要用于基于web的mvc3 .net应用程序,您会推荐哪个验证框架? 应用程序遵循领域模型模式,领域模型POCO在单独的类库中?
需要的验证类型将是...非空、基于正则表达式等。
我会选择FluentValidation,这是一个很棒的开源项目。
https://github.com/JeremySkinner/FluentValidation
它同样适用于基本和更复杂的验证。
"未提供社会安全号码"
而不是"逐个检查"。(逐个检查可能需要多次才能最终确定您的支票的有效性)。
以下是一些示例代码。假设有人试图购买ISBN为“ABC123456”的书籍。
下面是一个自定义规则,用于检查该书是否存在(例如,在您的产品数据库中)。我认为你可以跟上。它将与Book(.cs) poco对象连接在一起。(没有显示任何“连接”)。我只是试图给你一个简单规则的快速示例,以展示创建简单规则的难易程度。
当找不到一本书(使用isbn)时...那么您会看到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;
}
}
}