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.
Make the non-required fields nullable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With