我正在使用我在此处发布的自己的验证库。
您建议的两者的区别在于验证被放入单独的验证类中。您可以创建并忘记验证类,它们由验证库自动发现。
public class MyModelValidator : FluentValidator<MyModel>
{
public MyModelValidator()
{
Property("FirstName").Required();
Property("LastName").Required().Min(15);
}
}
使用您自己喜欢的本地化库(例如字符串表)添加对本地化的支持也很容易
public class StringTableProvider : ILanguagePrompts
{
public string this[string modelName, string propertyName]
{
get { return Get(modelName, propertyName) ?? "[" + propertyName+ "]"; }
}
public string Get(string modelName, string propertyName)
{
return Resource1.ResourceManager.GetString(modelName + "_" + propertyName);
}
}
并配置:
Validator.LanguageHandler = new StringTableProvider();
实际验证是这样完成的:
User user = new User();
user.FirstName = "Jonas";
var errors = Validator.Validate(user);
if (errors.Count > 0)
{
// Handle the errors in any way you like.
// both property names (localized and actual property name) and localized error message is accessible.
}