'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.
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user3711357 |
Solution 2 | Sinan Bozku? |