thrashead
thrashead

Reputation: 337

ModelState does not work properly

I have a very simple application. Here's my view code;

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Kategori Modeli</legend>

    <div class="editor-label">
        Category Name
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.CategoryName)
        @Html.ValidationMessageFor(model => model.CategoryName)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>}

And here's my model code;

    public int ID { get; set; }
    [Required(ErrorMessage = "Category Name cannot be null.")]
    [Range(3, 25, ErrorMessage = "Category Name must have 3-25 characters")]
    public string CategoryName { get; set; }

And the Insert Code;

    [HttpPost, ValidateInput(false)]
    public ActionResult Insert(Category _category)
    {
        if (ModelState.IsValid)
        {
            ---
        }
    }

ModelState.IsValid is always false even if it has 4 characters. Please help me. It always shows "Category Name must have 3-25 characters" error message.

Upvotes: 1

Views: 100

Answers (1)

Steve Harris
Steve Harris

Reputation: 5109

Range does not validate a string length. It checks a numeric value is between the specified numbers.

MaxLength and MinLength should be used.

Upvotes: 2

Related Questions