简体   繁体   中英

How to apply Client Side validation using Fluent Validation for .Net core

.Net Core 3.0 MVC view. Needs to apply - Client Side validation for below model.

Tried as follow:

Model:Person

public class Person {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
    }

Validation Rules:

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull().NotEmpty();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}

Followed documentation, it shows, "validator" attribute but I could not find in namespace.

https://docs.fluentvalidation.net/en/latest/mvc5.html

Was able to figure it out.

this needs to be added under, Startup file, .AddMvc().AddFluentValidation()

So, it automatically able to pick the validation at client side as well as server side. Thanks.

You need to add.AddFluentValidation() after.AddMvc() (or.AddControllersWithViews()) to enable Fluent Validation.

Fluent Validation supports some basic client-side validations like required, maxlength etc. If you want to use all server-side validations on client-side, you need to use third party libraries like FormHelper.

Form Helper helps you to create ajax forms and validations without writing any javascript code. It transforms server-side validations to client-side. It's very to use just add.AddFormHelper() and.UseFormHelper() on Startup.cs.

FormHelper: https://nuget.org/packages/FormHelper

Document: https://github.com/sinanbozkus/formhelper

Solution 1: Use AddFluentValidationClientsideAdapters

You may use the FluentValidation.AspNetCore and register the client-side validation by adding:

services.AddFluentValidationClientsideAdapters();

Solution 2: Use FormHelper

You may also use the FormHelper and, instead of using client-side validation you could instead execute your full server-side rules via AJAX .

Details

The FluentValidation GitHub readme says:

Clientside Validation

FluentValidation is a server-library and does not provide any client-side validation directly. However, it can provide metadata which can be applied to the generated HTML elements for use with a client-side framework such as jQuery Validate in the same way that ASP.NET's default validation attributes work.

Note that not all rules defined in FluentValidation will work with ASP.NET's client-side validation. For example, any rules defined using a condition (with When/Unless), custom validators, or calls to Must will not run on the client side. Nor will any rules in a RuleSet (although this can be changed - see below). The following validators are supported on the client:

  • NotNull / NotEmpty
  • Matches (regex)
  • InclusiveBetween (range)
  • CreditCard
  • Email
  • EqualTo (cross-property equality comparison)
  • MaxLength
  • MinLength
  • Length

To enable clientside integration you need to install the FluentValidation.AspNetCore package and call the AddFluentValidationClientsideAdapters in your application startup:

 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddFluentValidationClientsideAdapters(); services.AddScoped<IValidator<Person>, PersonValidator>(); // etc }

Note that the AddFluentValidationClientsideAdapters method is only available in FluentValidation 11.1 and newer. In older versions, you should use the AddFluentValidation method which enables both auto-validation and clientside adapters. If you only want clientside adapters and don't want auto validation in 11.0 and older, you can configure this by calling services.AddFluentValidation(config => config.AutomaticValidationEnabled = false)

Alternatively, instead of using client-side validation you could instead execute your full server-side rules via AJAX using a library such as FormHelper . This allows you to use the full power of FluentValidation, while still having a responsive user experience.

Specifying a RuleSet for client-side messages

If you're using rulesets alongside ASP.NET MVC, then you'll notice that by default FluentValidation will only generate client-side error messages for rules not part of any ruleset. You can instead specify that FluentValidation should generate clientside rules from a particular ruleset by attributing your controller action with a RuleSetForClientSideMessagesAttribute :

 [RuleSetForClientSideMessages("MyRuleset")] public ActionResult Index(){ return View(new Person()); }

You can also use the SetRulesetForClientsideMessages extension method within your controller action, which has the same affect:

 public ActionResult Index() { ControllerContext.SetRulesetForClientsideMessages("MyRuleset"); return View(new Person()); }

You can force all rules to be used to generate client-side error message by specifying a ruleset of "*".

Read more

Read more at:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM