【发布时间】:2019-08-21 12:02:01
【问题描述】:
我正在使用 FluentValidation 进行服务器端验证。现在我想使用 must 调用一个函数。
这是表单代码sn-p:
<form method="post"
asp-controller="Category"
asp-action="SaveSpecification"
role="form"
data-ajax="true"
data-ajax-loading="#Progress"
data-ajax-success="Specification_JsMethod">
<input asp-for="Caption" class="form-control" />
<input type="hidden" asp-for="CategoryId" />
<button class="btn btn-primary" type="submit"></button>
</form>
我应该对下面的代码进行哪些更改以调用函数 SpecificationMustBeUnique ?
public class SpecificationValidator : AbstractValidator<Specification>
{
public SpecificationValidator()
{
RuleFor(x => new { x.CategoryId, x.Caption}).Must(x => SpecificationMustBeUnique(x.CategoryId, x.Caption)).WithMessage("not unique");
}
private bool SpecificationMustBeUnique(int categoryId, string caption)
{
return true / false;
}
}
提示:1 - CategoyId 和 Caption 的组合应该是唯一的 2 - 提交表单时未完成验证(提交表单时验证未运行)
【问题讨论】:
-
CategoryId 和 Caption 的组合是否应该是唯一的?您是否收到异常或编译器错误?提交表单时验证是否未运行?目前尚不清楚您需要解决什么问题。
-
见官方文档中的Predicate Validator。
-
提示:1 - CategoyId 和 Caption 的组合应该是唯一的 2 - 提交表单时不做验证
标签: fluentvalidation fluentvalidation-2.0