Rob*_*nik 10 validation asp.net-mvc xval data-annotations
我的解决方案有这些项目:
DAL,BL和WEB都参考了很棒的DTO.
该过程通常以这种方式执行:
我的DTO能够根据自己的状态(属性值)验证自己.但是现在我遇到了问题,但事实并非如此.我需要他们使用BL(以及因此DAL)进行验证.
我的现实生活中的例子:用户注册和WEB获得验证的用户DTO.有问题的部分是username验证.应根据数据存储检查其唯一性.
我该怎么做?
还有其他信息表明所有DTO都实现了IoC和TDD 的接口(即UserDTO实现IUser).两者都是DTO项目的一部分.
Compilation errorPartial classes can't span assemblies.ActionFilter,可以根据外部条件验证对象.这个将在WEB项目中创建,因此可以看到将在此处使用的DTO和BL.我会建议一个实验,我在过去一周左右只进行了试验.
基于这种灵感,我创建的DTO与该DataAnnotations方法的验证方式略有不同.样本DTO:
public class Contact : DomainBase, IModelObject
{
public int ID { get; set; }
public string Name { get; set; }
public LazyList<ContactDetail> Details { get; set; }
public DateTime Updated { get; set; }
protected override void ConfigureRules()
{
base.AddRule(new ValidationRule()
{
Properties = new string[] { "name" },
Description = "A Name is required but must not exceed 300 characters in length and some special characters are not allowed",
validator = () => this.Name.IsRequired300LenNoSpecial()
});
base.AddRule(new ValidationRule()
{
Properties = new string[] { "updated" },
Description = "required",
validator = () => this.Updated.IsRequired()
});
}
}
Run Code Online (Sandbox Code Playgroud)
这可能看起来比工作更好DataAnnotations,这是因为它是,但它并不大.我认为它在课堂上更具代表性(我现在有一些非常难看的DTO课程,带有DataAnnotations属性 - 你甚至不能再看到这些属性).在这个应用程序中匿名代表的力量几乎是值得预订的(所以我发现).
基类:
public partial class DomainBase : IDataErrorInfo
{
private IList<ValidationRule> _rules = new List<ValidationRule>();
public DomainBase()
{
// populate the _rules collection
this.ConfigureRules();
}
protected virtual void ConfigureRules()
{
// no rules if not overridden
}
protected void AddRule(ValidationRule rule)
{
this._rules.Add(rule);
}
#region IDataErrorInfo Members
public string Error
{
get { return String.Empty; } // Validation should call the indexer so return "" here
} // ..we dont need to support this property.
public string this[string columnName]
{
get
{
// get all the rules that apply to the property being validated
var rulesThatApply = this._rules
.Where(r => r.Properties.Contains(columnName));
// get a list of error messages from the rules
StringBuilder errorMessages = new StringBuilder();
foreach (ValidationRule rule in rulesThatApply)
if (!rule.validator.Invoke()) // if validator returns false then the rule is broken
if (errorMessages.ToString() == String.Empty)
errorMessages.Append(rule.Description);
else
errorMessages.AppendFormat("\r\n{0}", rule.Description);
return errorMessages.ToString();
}
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
ValidationRule 和我的验证功能:
public class ValidationRule
{
public string[] Properties { get; set; }
public string Description { get; set; }
public Func<bool> validator { get; set; }
}
/// <summary>
/// These extention methods return true if the validation condition is met.
/// </summary>
public static class ValidationFunctions
{
#region IsRequired
public static bool IsRequired(this String str)
{
return !str.IsNullOrTrimEmpty();
}
public static bool IsRequired(this int num)
{
return num != 0;
}
public static bool IsRequired(this long num)
{
return num != 0;
}
public static bool IsRequired(this double num)
{
return num != 0;
}
public static bool IsRequired(this Decimal num)
{
return num != 0;
}
public static bool IsRequired(this DateTime date)
{
return date != DateTime.MinValue;
}
#endregion
#region String Lengths
public static bool IsLengthLessThanOrEqual(this String str, int length)
{
return str.Length <= length;
}
public static bool IsRequiredWithLengthLessThanOrEqual(this String str, int length)
{
return !str.IsNullOrTrimEmpty() && (str.Length <= length);
}
public static bool IsRequired300LenNoSpecial(this String str)
{
return !str.IsNullOrTrimEmpty() &&
str.RegexMatch(@"^[- \r\n\\\.!:*,@$%&""?\(\)\w']{1,300}$",
RegexOptions.Multiline) == str;
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
如果我的代码看起来很乱,那是因为我过去几天只是在研究这种验证方法.我需要这个想法来满足一些要求:
IDataErrorInfo接口,以便我的MVC层自动验证我想这种方法可以让我得到我想要的东西,也许你也是.
我想象一下,如果你和我一起加入我们的行列,我们就会"独自一人",但这可能是值得的.我正在阅读MVC 2中的新验证功能,但如果没有自定义修改,它仍然不符合上述愿望清单.
希望这可以帮助.
我最终使用了控制器操作过滤器,它能够根据无法从对象本身获取的外部因素来验证对象。
我创建了一个过滤器,它采用要检查的操作参数的名称和将验证该特定参数的验证器类型。当然,这个验证器必须实现某些接口才能使其可重用。
[ValidateExternalFactors("user", typeof(UserExternalValidator))]
public ActionResult Create(User user)
Run Code Online (Sandbox Code Playgroud)
验证器需要实现这个简单的接口
public interface IExternalValidator<T>
{
bool IsValid(T instance);
}
Run Code Online (Sandbox Code Playgroud)
对于看似复杂的问题,这是一个简单而有效的解决方案。
| 归档时间: |
|
| 查看次数: |
5042 次 |
| 最近记录: |