7

I have a form that is generated by ASP.NET. I have some required fields, and I am using the [Required] dataAnnotation for that. However, the elements that don't have the [Required] DataAnnotation are also required according to my webpage. These are not required at all yet I cannot submit the form if they are empty.

I used scaffolding to make the pages, jquery validator is used (by default) for the validation.

Model class (some fields have been omitted for clarity)

public class Room
{
    [Key]
    public int ID { get; set; }


    [Required(ErrorMessage = "Please enter the minimum (default) price for this room.")]
    [DataType(DataType.Currency)]
    [Display(Name = "Minimum price")]
    public decimal MinPrice { get; set; }

    [Display(Name = "Alternative price")]
    [DataType(DataType.Currency)]
    public decimal AltPrice { get; set; }
}

The code that creates the form fields in de .cshtml file:

    <div class="form-group">
        @Html.LabelFor(model => model.MinPrice, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.MinPrice)
            @Html.ValidationMessageFor(model => model.MinPrice)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.AltPrice, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.AltPrice)
            @Html.ValidationMessageFor(model => model.AltPrice)
        </div>
    </div>

The required field correctly displays the error message as defined (thus it reads the annotations). The non required field displays a generic error message instead ("The Alternative price field is required.").

I've searched quite a lot, but everywhere it says that if the [Required] DataAnnotation is not there, it won't be required in the form.

2 Answers 2

16

Make the non-required fields nullable.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah of course, thanks! I cannot accept the answer yet but I will as soon as I can.
Then what is the point of [Required] attribute?
3

I was having the same problem. I had to go into my model and put ? marks in the int fields to make them null. The fields that were set as string were fine it was just the int fields that were causing the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.