列表中可选对象的FluentValidation



对于列表中可能不存在的对象,是否有方法使用对象属性值来使用FluentValidation?我认为这是可能的,但我不知道如何编码。使用下面的代码示例,如果操作记录的操作值为"批准",是否可以确保电子邮件字段不为空?为了便于论证,假设我们不希望此规则应用于列表中可能在Action字段中具有不同值的其他对象。

class Action_Record
{
public string Type { get; set; }
public string Action { get; set; }
public string Comments { get; set; }
public string Action_By_Email { get; set; }
public DateTime? Action_Start { get; set; }
public DateTime? Action_End { get; set; }
public Action_Record()
{
this.Type = "";
this.Action = "";
this.Comments = "";
this.Action_By_Email = "";
this.Action_Start = null;
this.Action_End = null;
}
}
Approver_Recs = new List<Action_Record>();
Action_Record o = new Action_Record();
o.Type = "Finance";
o.Action = "Approve";
Approver_Recs.Add(o);

使用最新版本的"FluentValidation",这应该可以工作:

创建一个将集合对象作为输入的验证器类。然后,只有在Action="Approve"的情况下,我们才会调用EmailValidator。

public class ActionRecordValidator : AbstractValidator<List<Action_Record>>
{
public ActionRecordValidator()
{
RuleForEach(x => x).Where(x => x.Action == "Approve").SetValidator(new EmailValidator());
}
}
public class EmailValidator : AbstractValidator<Action_Record>
{
public EmailValidator()
{
RuleFor(x => x.Action_By_Email).NotNull().NotEmpty().WithMessage("Email is required when Approve action is chosen.");
}
}

调用代码示例:

var Approver_Recs = new List<Action_Record>();
Action_Record o = new Action_Record() { Type = "Finance" , Action = "Reject" };
Approver_Recs.Add(o);
Action_Record o2 = new Action_Record() { Type = "Finance" , Action = "Approve" };
ActionRecordValidator validator = new ActionRecordValidator();
Approver_Recs.Add(o2);
ValidationResult results = validator.Validate(Approver_Recs);
if (!results.IsValid)
{
foreach (var failure in results.Errors)
{
Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
}
}

相关内容

  • 没有找到相关文章

最新更新