I have been searching through the stackoverflow website for an answer to my question, but I couldn't find a proper solution. So I hope I can get the solution this way.
Situation: I have a form with several fields; 2 of them are required: one of them is an EnumDropDownListFor which has an extra 'empty option'.
Problem: The validation of the dropdownlist triggers on the change event of the dropdown/when the empty option has been selected.
Wanted behavior: Only validate the dropdownlist when the form is submitted and NOT on the change event.
Here is my code:
public class SearchOrderViewModel
{
[Required]
[Display(Name = "Supplier", ResourceType = typeof(SearchOrderStrings))]
public string Supplier { get; set; }
[Required]
[Range(1, int.MaxValue, ErrorMessageResourceType = typeof(SearchOrderStrings), ErrorMessageResourceName = "OrderTypeRequired")]
[Display(Name = "OrderType", ResourceType = typeof(SearchOrderStrings))]
public OrderTypeEnum OrderType { get; set; }
[Display(Name = "PurchasingReason", ResourceType = typeof(SearchOrderStrings))]
public int PurchasingReason { get; set; }
}
public enum OrderTypeEnum
{
OpenOrder = 1,
ClosedOrder = 2
}
Index.cshtm
<div id="divExternalSupplierSearch" class="form-group">
@Html.LabelFor(model => model.Supplier)
@Html.ValidationMessageFor(model => model.Supplier)
<div id="divDropdown">
@Html.DropDownListFor(model => model.Supplier,
Model.SupplierCodes, new { @class = "form-control" })
</div>
</div>
<div id="divOrderTypes" class="form-group">
@Html.LabelFor(model => model.OrderType)
@Html.ValidationMessageFor(model => model.OrderType)
<div id="divDropdown">
@Html.EnumDropDownListFor(model => model.OrderType, new { @class = "form-control" })
</div>
</div>
<div id="divPurchasingReasons" class="form-group">
@Html.LabelFor(model => model.PurchasingReason)
<div id="divDropdown">
@Html.DropDownListFor(model => model.PurchasingReason, Model.PurchasingReasons, new { @class = "form-control" })
</div>
</div>
If more information is needed, let me know.
Thanks
EDIT (Solution):
By combining @Elmer Dantas answer and trying some things, I found that I could become the wanted behaviour by removing the [Range] data-annotation and making the OrderType property in my SearchOrderViewModel nullable.
So this code is only validating the OrderType value on submit of the form:
[Required]
[Display(Name = "OrderType", ResourceType = typeof(SearchOrderStrings))]
public OrderTypeEnum? OrderType { get; set; }
Apparently the
[Range(1, int.MaxValue, ErrorMessageResourceType = typeof(SearchOrderStrings), ErrorMessageResourceName = "OrderTypeRequired")]
data-annotation was checking if the value was valid on the change event of the dropdownlist. By making the property nullable and just keeping the [Required] data-annotation, I could keep the validation to only be triggered when submitting the form.