如何从api post方法中访问FluentValidation错误?

时间:2018-11-28 04:16:23

标签: .net-core fluentvalidation

Fluent Validation docs中 有一个例子

    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.

//如何在此处获取验证器错误消息?

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

验证器设置为

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

假设验证失败。如何从Create方法中访问“验证错误”?

我问是因为我将FluentValidation与API结合使用,并且需要API传达验证错误的方法。

1 个答案:

答案 0 :(得分:0)

检查ModelState是否存在错误(True / False)

<% YourModel.ModelState.IsValid %>

检查特定的属性错误

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

检查所有错误

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

这里有很多关于此问题的好答案。 这是link的一对,这里是another