Question

I'm using FluentValidation MVC5 for validating the object. I've followed this tutorial. When I post the form, why MVC DefaultModelBinder does not validate the object? FluentValidationModelValidatorProvider is already configured in global.asax

Global.asax

protected void Application_Start()
{
    FluentValidationModelValidatorProvider.Configure();
}

ClientValidationEnabled and UnobtrusiveJavaScriptEnabled is set true in web.config. I've also downloaded latest jquery.validation package, add to BundleConfig, and in its view (Create.cshtml) I've added

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

CurrencyViewModel.cs

[Validator(typeof(CurrencyViewModelValidator))]
public class CurrencyViewModel
{
    public int CurrencyID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

public class CurrencyViewModelValidator : AbstractValidator<CurrencyViewModel>
{
    public CurrencyViewModelValidator()
    {
        RuleFor(x => x.Code).Length(3);
        RuleFor(x => x.Name).Length(3, 50);
    }
}

CurrencyController.cs

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CurrencyViewModel currencyVM)
{
    if (ModelState.IsValid)
    {
        Currency currency = new Currency()
        {
            Code = currencyVM.Code,
            Name = currencyVM.Name
        };

        db.Currencies.Add(currency);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

    return View(currencyVM);
}
Was it helpful?

Solution

The values in currency are null, but ModelState.IsValid is true, weird.

This is completely normal behavior. The validator checks for a string length, not whether a property is null. Documentation:

Ensures that the length of a particular string property is within the specified range.

If you do not want to allow null values you should use NotNull validator:

RuleFor(x => x.Code).NotNull().Length(3);
RuleFor(x => x.Name).NotNull().Length(3, 50);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top