Cristiano
Cristiano

Reputation: 3189

ASP.NET MVC4 Code First - Data validation doesn't work

I have problem with data validation in forms. I declare error messages in model but it seems that it doesn't have any effect in the View. I have the following model:

public class Dog
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Id")]
    public int Id { get; set; }

    [Display(Name = "Name")]
    [StringLength(20)]
    public string Name { get; set; }

    [Display(Name = "Value")]
    [Range(1, int.MaxValue, ErrorMessage="Minimum value is 1")]
    public int Value { get; set; }
}

And in View I have this:

<div class="editor-field">
@Html.EditorFor(model => model.Value)
@Html.ValidationMessageFor(model => model.Value)
</div>

The problem is that there is no error message when user chooses to enter number which is lower than 1 as you can see here:

enter image description here

What am I missing here? Thank you for your help.

Upvotes: 3

Views: 1265

Answers (2)

Icarus
Icarus

Reputation: 63956

As requested in the comments, I am adding this as the answer:

Add a reference to the jQuery Validation plugin

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

Judging by the no tags, no references or any mentions of jQuery validation, we can safely see you're trying to validate the good old fashioned way (the out of the box way).

You have to invoke the validation yourself in your post method, by calling ModelState.IsValid. If that fails, the error messages will show on the erroneous fields. You'd had something like this:

[HttpPost]
public ActionResult Edit (Dog model)
{
    if (ModelState.IsValid)
    {
        //He's a good dog, save him, then redirect elsewhere
    }
    else
    {
        //He's a bad dog, return the same view and the errors are shown
        return View(model);
    }
}

Upvotes: 3

Related Questions