开发者

Fluent Validation on AJAX Form

I am creating an action/view in ASP.net MVC that I would like to POST using AJAX / jQuery. I am using Fluent Validation for the validation in my view models.

Is it possible to have client side validation when I do this? What would the script look like in order to trigger this client side validation using fluent validation?

Do I create a regular form and create a submit event using jquery and call something or wou开发者_StackOverflow中文版ld I just Ajax.BeginForm() instead?


I use the jQuery unobtrusive validation with data annotations but it looks like you need the same settings as me (the first two options below) plus another step:

  • Enable client validation in your view or web.config
  • Enable unobtrusive validation in your view or in web.config
  • Add the FluentValidationModelValidatorProvider to the ModelValidatorProviders collection

For the first two, see Enabling Client-Side Validation. For the last one see Fluent Validation: Integration with ASP.NET MVC.

If you want to submit the form via AJAX, you can trigger the validation on the whole form with $('#form_selector').valid() or on an individual input with $('#input_selector').valid(). The calls to valid() return true if the validation is successful (and false if not).


Fluent Validation is a server-side validation library. Because of this, Fluent Validation supports some basic client-validations (like required, maxlength etc.) You can't use all server-side rules on client-side.

If you want to add fully client-side support to Fluent Validation, you need to add one more library to your project. Form Helper can be a solution for your problem.

https://github.com/sinanbozkus/FormHelper

You need to create your forms like this:

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

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

@await Html.RenderFormScript(formConfig)

After that you need to add [FormValidator] attribute to your action.

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

Now all Fluent Validation rules work on client-side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜