假设我有一个值对象类FullName,它在Employee实体类中用作属性。 FullName可能有一个中间名,昵称等;但是从域的角度来看,我只想强制执行FullName的FirstName和LastName属性。
我想将此表达为EmployeeValidator的一部分:ValidationDef {Employee}对象,而不是属性。
我是否首先需要为FullName创建一个类验证器(即FirstAndLAstNameRequired),然后说Employee中的FullName属性是有效的(使用一些有效的ValidAttribute形式)?
顺便说一下,似乎this documentation仍然是最好的,但它确实看起来已经过了三年。我错过了哪些更新的东西?
干杯,
Berryl
我还没有想到这一点,但我在这里找到了NHib验证器信息的最佳来源:http://fabiomaulo.blogspot.com/search/label/Validator
这里有一些伪代码可以更好地表达这个问题:
/// <summary>A person's name.</summary>
public class FullName
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string MiddleName { get; set; }
public virtual string NickName { get; set; }
}
public class EmployeeValidator : ValidationDef<Employee>
{
public EmployeeValidator()
{
Define(x => x.FullName).FirstAndLastNameRequired(); // how to get here!!
}
}
public class FullNameValidator : ValidationDef<FullName>
{
public FullNameValidator() {
Define(n => n.FirstName).NotNullable().And.NotEmpty().And.MaxLength(25);
Define(n => n.LastName).NotNullable().And.NotEmpty().And.MaxLength(35);
// not really necessary but cool that you can do this
ValidateInstance
.By(
(name, context) => !name.FirstName.IsNullOrEmptyAfterTrim() && !name.LastName.IsNullOrEmptyAfterTrim())
.WithMessage("Both a First and Last Name are required");
}
}
public class EmployeeValidator : ValidationDef<Employee>
{
public EmployeeValidator()
{
Define(x => x.FullName).IsValid(); // *** doesn't compile !!!
}
}
答案 0 :(得分:1)
要在验证员工时验证FullName,我认为您会执行以下操作:
public class EmployeeValidator : ValidationDef<Employee>
{
public EmployeeValidator()
{
Define(x => x.FullName).IsValid();
Define(x => x.FullName).NotNullable(); // Not sure if you need this
}
}
然后FullName Validator就像:
public class FullNameValidator : ValidationDef<FullName>
{
public EmployeeValidator()
{
Define(x => x.FirstName).NotNullable();
Define(x => x.LastName).NotNullable();
}
}
或者我认为你可以做一些事情(没有检查语法):
public class EmployeeValidator: ValidationDef<Employee>
{
public EmployeeValidator() {
ValidateInstance.By((employee, context) => {
bool isValid = true;
if (string.IsNullOrEmpty(employee.FullName.FirstName)) {
isValid = false;
context.AddInvalid<Employee, string>(
"Please enter a first name.", c => c.FullName.FirstName);
} // Similar for last name
return isValid;
});
}
}