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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.