Question

I am working with dataannotations and I have applied a range validator but the error message in the validator is not working. It is defaulted to "The Code1 field is required" ..

View Page::

  @Html.DropDownListFor(m => m.Code1, Model.Codes, "Select", new { })
                      @Html.ValidationMessageFor(mbox => mbox.Code1)

model
  [Range(1, 250, ErrorMessage = "code field is required")]
        public int Code1 { get; set; }

I do not know why my defined error message is not showing up.

I have also tried in changing the message in view page:

View Page::

  @Html.DropDownListFor(m => m.Code1, Model.Codes1, "Select","Code is required", new { })

Now, the message defined here is working but it is giving me a weird behaviour. It shows the above given message in black and white and just changes to red when the Validation fires and when I change a value in dropdown it again becomes black and white.

enter code here

Was it helpful?

Solution

Use the required validator instead of the range validator for compulsory entry.

    [Required(ErrorMessage = "Code1 is required")]
    [Range(1, 250, ErrorMessage = "Value must be between 1 and 250")]
    public int Code1 { get; set; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top