Dynamically Adjusting Form Field Validation Based on Available Options in the DropDownList Editor
Environment
Product | Telerik UI for ASP.NET Core Form |
Product | Telerik UI for ASP.NET Core DropDownList |
Product Version | 2024.3.806 |
Description
How can I dynamically set the fields in a Form as required or non-required based on the available options in their DropDownList editors?
When using Telerik UI for ASP.NET Core Form, which contains Telerik UI for ASP.NET Core DropDownList editors that bind to remote data, you can make the fields non-required in cases when no options are received from the server. Otherwise, the users will be forced to select an option to submit the Form.
Solution
- Subscribe to the
RequestEnd
event of the DataSource of each DropDownList editor using a template delegate. - Within the inline event handler, access the event data and pass it to a JavaScript function along with the name of the field to which the DropDownList binds.
- Within the JavaScript function validateField, check if there are available options received from the server and set the attribute
required
to the input element of the respective field with jQuery. - Reuse the validateField function for all DropDownList editors that loads data from the server.
@(Html.Kendo().Form<FormItems>()
.Name("exampleForm")
.HtmlAttributes(new { action = "Items", method = "POST" })
.Items(i =>
{
i.Add()
.Field(f => f.EquipmentType)
.Label(l => l.Text("Equipment Type"))
.Editor(e =>
{
e.DropDownList()
.DataTextField("ShortName")
.DataValueField("EquipmentTypeID")
.OptionLabel("Select")
.DataSource(source =>
{
source
.Read(read => { read.Action("GetItems","Home"); })
.Events(ev => ev.RequestEnd(@<text> // Subscribe to the event by a template delegate.
function(eventData) { // Access the event data.
return validateField(eventData, "EquipmentType"); // Pass the event data and the name of the field to the custom function.
}
</text>));
});
});
})
)
@addTagHelper *, Kendo.Mvc
@model FormItems
<kendo-form name="exampleForm" form-data="@Model" method="POST" asp-action="Items">
<form-items>
<form-item field="EquipmentType">
<item-label text="Equipment Type:" />
<dropdownlist-editor placeholder="Select" datatextfield="ShortName" datavaluefield="EquipmentTypeID">
<datasource on-request-end="function(eventData) {
return validateField(eventData, 'EquipmentType');
}">
<transport>
<read url="@Url.Action("GetItems", "Home")"/>
</transport>
</datasource>
</dropdownlist-editor>
</form-item>
</form-items>
</kendo-form>
<script>
function validateField(eventData, fieldName) { // Reuse this handler for all editors that loads data from the server.
if (eventData.response.length > 0) {
$("#" + fieldName).attr("required", "required");
} else {
$("#" + fieldName).removeAttr("required");
}
}
</script>