【发布时间】:2021-08-03 06:23:53
【问题描述】:
目前正在向我的项目添加验证,我遇到了 Fluent Validation,我创建了这样的验证器:
using Dealership.App.Models.CarBrand;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Dealership.App.FluentValidation
{
public class CarBrandValidator : AbstractValidator<CreateCarBrandViewModel>
{
public CarBrandValidator()
{
RuleFor(brand => brand.CarBrandName).NotNull()
.WithMessage("Car Brand needs to have a name");
}
}
}
正如文档所建议的那样,我在启动文件中对其进行了如下配置:
services.AddMvc()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
现在这是我应用验证的控制器中的操作方法
public async Task<IActionResult> CreatePost(CreateCarBrandViewModel newBrand)
{
if(ModelState.IsValid)
{
var response = await _mediator.Send(new CreateCarBrandCommand(newBrand));
if (response)
{
this._unitOfWork.Commit();
}
return RedirectToAction("Index");
}
return RedirectToAction("Create");
}
这是我的观点:
@model Dealership.App.Models.CarBrand.CreateCarBrandViewModel
<div asp-validation-summary="ModelOnly"></div>
<form asp-action="CreatePost" method="POST">
<div class="form-group">
<label for="BrandName">Brand Name</label>
<input asp-for="CarBrandName" class="form-control col-4" id="BrandName" placeholder="Enter Car Brand name" />
<span asp-validation-for="CarBrandName"></span>
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
事情是这样的,我的验证工作 50%,我的意思是如果我在验证器中指定的字段为空,验证工作在方面,它将再次重定向回同一页面,一切都很好。 但是我想显示我在验证器中设置的错误消息,我已经尝试了很多东西并阅读了很多东西,如果有人可以提供帮助,那就太棒了
提前致谢
【问题讨论】:
-
可以分享一下吗?
-
我确实可以,见上
标签: c# asp.net-core fluentvalidation