1

Let's say I created a model with a property as int? type.

public class MyModel
{
    [Range(-100, 100, ErrorMessage="Too large")]
    public int? MyValue { get; set; }
}

In the view I use it for a text box in the form to post back to server.

    @using (Html.BeginForm())
    {
        <p>Enter some value</p>
        <div>@Html.TextBoxFor(m => m.MyValue)</div>
        <div>@Html.ValidationMessageFor(m => m.MyValue)</div>
        <input type="submit" value="Submit" />
    }

Here is the controller code

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyModel model)
    {
        return View(model);
    }
}

Now if I enter an extremely large number in the text box, e.g 111111111111111111111111111111111111111111111111111111111111111111111111111111, which is for sure too large for an integer data type. On post back, got message The value '111111111111111111111111111111111111111111111111111111111111111111111111111111' is invalid.

But I have no way to use the error message (localization and so on) I defined in my model.

hardywang
  • 4,864
  • 11
  • 65
  • 101
  • Your users could just as easily have entered 'abcdefg' into the textbox unless you are doing some client side validation. You should check `ModelState.IsValid` on your controller and handle a false with output to the user. But really, you should be doing something clientside as well to maybe only allow numbers in the textbox and set an upper limit? – Lotok Apr 01 '15 at 14:45
  • Yes, model state is invalid for sure. This is just my testing code, I ignored it anyway. – hardywang Apr 01 '15 at 15:24
  • Because the value you entered is outside the range for an `int` so the `..is invalid` error is generated first (before your `range` validation) –  Apr 02 '15 at 00:14

1 Answers1

1
using System.ComponentModel.DataAnnotations;
    public class MyModel
{
    [Range(int.MinValue, int.MaxValue)]
    public int? MyValue {get; set; }
}

That should do the trick.

Wigle
  • 96
  • 9