我有一个非常简单的验证器类,下面包含了它。该验证器类验证QuestionAnswer
对象,以确保其属性有效。
对于某些问题,这些条件取决于先前的问题。这意味着如果上一个问题没有得到回答,那么当前问题必须为空,因为它不能接受答案。
例如,如果问题Y以问题X为条件,并且X的答案为空,那么Y的答案也必须为空。
这是验证器中的最后一条规则已被检查的内容。但是,当我传入以上一个问题为条件的QuestionAnswer
却没有回答上一个问题时,该规则不会执行。例如以下输入:
验证100
Id:100
Section: 6
Type: no-type
Required: True
Text: Question 100
Answer: Mr
Conditional Question Id: 99
Conditional Question Answer:
上面的QuestionAnswer
对象没有任何错误地通过了验证,但是正如我们看到的那样,该问题取决于问题99,该问题尚未得到回答,因此应该会通过验证。
QuestionAnswer类
class QuestionAnswer
{
private string _type;
public int Id { get; set; }
public string Text { get; set; }
public string Type
{
get => _type;
set => _type = ConvertFromJsonType(value);
}
public bool Required { get; set; }
public int Section { get; set; }
public string Answer { get; set; }
public string ConditionalQuestionId { get; set; }
public string ConditionalQuestionAnswered { get; set; }
}
QuestionAnswer验证器
class FluentQuestionAnswerValidator : AbstractValidator<QuestionAnswer>
{
public FluentQuestionAnswerValidator()
{
RuleFor(qa => qa.Answer).NotNull()
.When(qa => qa.Required == true)
.WithMessage("This answer is required and cannot be null.");
RuleFor(qa => qa.Answer).NotEmpty()
.When(qa => qa.Required == true)
.WithMessage("This answer is required and cannot be empty."); ;
RuleFor(qa => qa.Answer).Must(IsNotNullOrWhiteSpace)
.When(qa => qa.Required == true)
.WithMessage("This answer is required and cannot be null or contain whitespace.");
RuleFor(qa => qa.Answer).Empty()
.When(qa => qa.ConditionalQuestionId != null && qa.ConditionalQuestionAnswered == null)
.WithMessage("This question is required and conditional and therefore relies a previous question to be answered first.");
}
public bool IsNotNullOrWhiteSpace(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
return true;
}
}