Asp.Net MVC - FluentValidation

Is there a way in ASP.NET MVC to use some kind of smooth validation?

I mean, instead of checking my poco, like this:

public class User {

    [Required]
    public int Id { get; set; }

The presence of something like this (in the outer class):

User.Validate("Required", "Id");

Is this something possible in Asp.Net MVC 2 (or 3)?

I know that there is a FluentValidation library , but I would like to know if this allows something in the Asp.Net MVC core.

I do not like to pollute my POCO. Also, what happens if I need to check, let them say that BeginDate is before EndDate? With an attribute you cannot do this.

+3
source share
1 answer

FluentValidation ASP.NET MVC. , .

, :

[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
    public int? Id { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
    public MyViewModelValidator()
    {
        RuleFor(x => x.Id)
            .NotNull();
        RuleFor(x => x.EndDate)
            .GreaterThan(x => x.StartDate);
    }
}

:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // The model is valid => process it
        return RedirectToAction("Success");
    }
    // Validation failed => redisplay the view in order to show error
    // messages
    return View(model);
}
+9

Source: https://habr.com/ru/post/1771924/


All Articles