2

In the Fluent Validation docs There is an example

    public class PeopleController : Controller {
    public ActionResult Create() {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Person person) {

        if(! ModelState.IsValid) { // re-render the view when validation failed.

// How do I get the Validator error messages here?

            return View("Create", person);
        }

        TempData["notice"] = "Person successfully created";
        return RedirectToAction("Index");

    }
}


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

Where the validator has been set up as

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);
    }
}

Suppose a validation fails. How can I access the Validation Error from within the Create method?

I ask because I am using FluentValidation with an API and need a way for the API to communicate validation errors.

Kirsten
  • 15,730
  • 41
  • 179
  • 318

1 Answers1

0

Check ModelState for errors ( True / False )

<% YourModel.ModelState.IsValid %>

Check for a specific Property error

<% YourModel.ModelState["Property"].Errors %>

Check for all errors

<% YourModel.ModelState.Values.Any(x => x.Errors.Count >= 1) %>

There are a ton of good answers to this question on here. Here is a link to one and here is another

RoninEngineer
  • 366
  • 2
  • 7
  • 18