OldKingKaiser
OldKingKaiser

Reputation: 23

ModelState.IsValid always evaluating as true when working with FluentValidation

I am a junior programmer trying to write a simple little bit of code to test out FluentValidation, but without manually calling the validator and adding the results to the modelstate with .AddToModelState, I cannot get the ModelState.IsValid to recognize there are errors in the validation. Am I missing integration somewhere?

This is my Value Model, just a string array with two preset values.

using FluentValidation.Attributes;
using Playground2.Validators;

namespace Playground2.Models
{
    [Validator(typeof(ValueValidator))]
    public class Value
    {
        public string[] values = { "value1", "" };
    }

}

This is my Validator, looking for two values between 5 and 10 characters.

using FluentValidation;
using Playground2.Models;

namespace Playground2.Validators
{
    public class ValueValidator : AbstractValidator<Value>
    {
        public ValueValidator()
        {
            RuleFor(x => x.values[0]).Length(5, 10);
            RuleFor(x => x.values[1]).Length(5, 10);
        }
    }
}

In the ValuesController, I am simply creating a value object and running a check to see if it passes validation before being output.

using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Playground2.Models;
using System.Collections.Generic;

namespace Playground2.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var value = new Value();

            if (!ModelState.IsValid)
            {
                return new string[] { "Not valid" };      
            }
            else
            {
                return value.values;
            }         
    }

But when run, the ModelState.IsValid is always evaluating as true, though the information fed into values is by default invalid.

Upvotes: 2

Views: 1324

Answers (1)

DiskJunky
DiskJunky

Reputation: 4971

FluentValidation follows MVC's/HTML's convention in regard to GETs and POSTs. In this case it's not expecting any validation to be done an a page's initial GET as a user wouldn't necessarily have performed any action. They're instead requesting the page to start doing something - they haven't gotten around to supplying data.

Once the user fills out information the convention is to submit the data in a HTML <form> using a <button> or <input type="submit"/> to submit the data to the controller via a HttpPost marked method. At this point validation has triggered and you'll be able to correctly interrogate the ModelState.IsValid.

Upvotes: 1

Related Questions