如何同时显示来自服务器端流利验证和客户端验证的错误消息?

时间:2018-11-12 10:34:50

标签: c# asp.net-core fluentvalidation

我有一条流利的验证规则:

public EmployeeAbsenceValidator() {
    RuleFor(a => a.DateTo)
        .GreaterThanOrEqualTo(a => a.DateFrom)
        .WithMessage("The end date cannot be before the start date.");
}

在控制器的Create POST方法中,我正在验证日期并保存到数据库,如果日期有效,则将其重定向到员工的详细信息视图,如果日期有效,则返回到create-absence-view不是:

if (ModelState.IsValid)
{
    EmployeeAbsenceValidator validator = new EmployeeAbsenceValidator();
    ValidationResult result = validator.Validate(employeeAbsence);
    if (result.IsValid)
    {
        _context.Add(employeeAbsence);
        await _context.SaveChangesAsync();
        return RedirectToAction("Details", "Employees");
    }
    else
    {
        result.AddToModelState(ModelState, null); // Passing error message to model state
        return View(employeeAbsence);
    }
}

这是create-absence-view:

<form asp-action="Create">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="row">
        <div class="form-group col-md-4">
            <label asp-for="Percentage" class="control-label"></label>
            <input asp-for="Percentage" class="form-control" />
            <span asp-validation-for="Percentage" class="text-danger"></span>
        </div>
    </div>
    <div class="row">
        <div class="form-group col-md-6">
            <label asp-for="DateFrom" class="control-label"></label>
            <input asp-for="DateFrom" class="form-control" />
            <span asp-validation-for="DateFrom" class="text-danger"></span>
        </div>
        <div class="form-group col-md-6">
            <label asp-for="DateTo" class="control-label"></label>
            <input asp-for="DateTo" class="form-control" />
            <span asp-validation-for="DateTo" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <button type="submit" value="Save">Save</button>
    </div>
</form>

如果正确填写了Percentage,并且DateToDateFrom之前,则会在日期上显示来自流利验证的错误消息。但是,如果Percentage无效,则仅显示Percentage上的客户端错误消息。我想这是因为服务器尚未知道日期的无效性,因为尚未提交表单。如何获得两个错误消息? (请告诉我,我不需要编写任何JQuery ...)

1 个答案:

答案 0 :(得分:0)

FluentValidation是服务器端框架。并非FluentValidation中定义的所有规则都可以与ASP.NET的客户端验证一起使用。但是,您可以将客户端验证支持添加到使用Form Helper库的Fluent验证中。

https://github.com/sinanbozkus/FormHelper

从Nuget软件包管理器中将FormHelper添加到您的项目中。

在startup.cs中注册FormHelper

services.AddFormHelper();

像这样创建表单:

var formConfig = new FormConfig(ViewContext)
{
    FormId = "ProductForm",
    FormTitle = "New Product",
    Callback = "ProductFormCallback" // optional,
};

// <form id="@formConfig.FormId" asp-controller="Home" asp-action="Save"
// ...

@await Html.RenderFormScript(formConfig)

并在保存操作中使用此属性进行客户端验证:

[HttpPost, FormValidator]
public IActionResult Save(FormViewModel viewModel)

可以使用了。

您可以在github页面上查看更多信息。