通过 AJAX 发送表单并通过 fluentValidation 进行验证
send the form via AJAX and do its validation via fluentValidation
我想通过 AJAX 发送表单并通过 mvc 核心中的 fluentValidation 进行验证。请指导我
这里有一个工作演示,您可以参考:
通过安装适当的 NuGet 包添加对 FluentValidation.AspNetCore
程序集的引用:
Install-Package FluentValidation.AspNetCore
通过在 ConfigureServices
方法中调用 AddFluentValidation
扩展方法,在应用程序的 Startup class 中配置 FluentValidation,并使用 AddFromAssemblyContaining
方法来自动注册特定程序集中的所有验证器
services.AddMvc()
.AddFluentValidation(fv => {
fv.RegisterValidatorsFromAssemblyContaining<PersonValidator>();
//If you want to disable this behaviour so that FluentValidation is the only validation library that executes,
//you can set the RunDefaultMvcValidationAfterFluentValidationExecutes to false in your application startup routine
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
假设 PersonValidator
被定义为验证一个名为 Person
的 class
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
控制器
[HttpPost]
public async Task<IActionResult> CreatPerson(Person person)
{
if (!ModelState.IsValid)
{ // re-render the view when validation failed.
return BadRequest();
}
//Save the person to the database, or some other logic
_context.Add(person);
await _context.SaveChangesAsync();
var message = "Person successfully created";
return Ok(message);
}
查看及相关jQuery
@model TestExample.Models.Person
<hr />
<div class="row">
<div class="col-md-4">
<form id="formdata">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$("#formdata").submit(function (e) {
e.preventDefault();
var form = $(this);
$.ajax(
{
type: "post",
url: "/people/CreatPerson",
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
});
});
</script>
}
关于 FluentValidation 的更多细节,您可以参考 https://fluentvalidation.net/aspnet
我想通过 AJAX 发送表单并通过 mvc 核心中的 fluentValidation 进行验证。请指导我
这里有一个工作演示,您可以参考:
通过安装适当的 NuGet 包添加对
FluentValidation.AspNetCore
程序集的引用:Install-Package FluentValidation.AspNetCore
通过在
ConfigureServices
方法中调用AddFluentValidation
扩展方法,在应用程序的 Startup class 中配置 FluentValidation,并使用AddFromAssemblyContaining
方法来自动注册特定程序集中的所有验证器services.AddMvc() .AddFluentValidation(fv => { fv.RegisterValidatorsFromAssemblyContaining<PersonValidator>(); //If you want to disable this behaviour so that FluentValidation is the only validation library that executes, //you can set the RunDefaultMvcValidationAfterFluentValidationExecutes to false in your application startup routine fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false; }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
假设
的 classPersonValidator
被定义为验证一个名为Person
public class Person { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public int Age { get; set; } } public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(x => x.Id).NotNull(); RuleFor(x => x.Name).Length(0, 10); RuleFor(x => x.Email).EmailAddress(); RuleFor(x => x.Age).InclusiveBetween(18, 60); } }
控制器
[HttpPost] public async Task<IActionResult> CreatPerson(Person person) { if (!ModelState.IsValid) { // re-render the view when validation failed. return BadRequest(); } //Save the person to the database, or some other logic _context.Add(person); await _context.SaveChangesAsync(); var message = "Person successfully created"; return Ok(message); }
查看及相关jQuery
@model TestExample.Models.Person <hr /> <div class="row"> <div class="col-md-4"> <form id="formdata"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Email" class="control-label"></label> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Age" class="control-label"></label> <input asp-for="Age" class="form-control" /> <span asp-validation-for="Age" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div>
@section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} <script> $("#formdata").submit(function (e) { e.preventDefault(); var form = $(this); $.ajax( { type: "post", url: "/people/CreatPerson", data: form.serialize(), success: function (data) { alert(data); }, error: function (data) { alert(data); } }); }); </script> }
关于 FluentValidation 的更多细节,您可以参考 https://fluentvalidation.net/aspnet