Articles in this section
Category / Section

How to set validation for a column based on another column value?

1 min read

You can set the validation rules to a column by using the Validation Rules property of the column in ASP.NET MVC Grid. In certain cases, to set validation to a column based on another column value that is, to set conditional validation to a column, refer to the following solution.

Solution

Consider a Grid with a checkbox column and based on the value of the checkbox, another column is to be enabled or disabled and accordingly the validation is also to be set for that column.

Example

To achieve the above requirement in Grid, refer to the following steps.

  1. Code for Template Edit form.

HTML

<script type="text/template" id="template">
<b>Order Details</b>
<table cellspacing="10">
<tr>
<td style="text-align: right;">
Order ID
</td>
<td style="text-align: left">
<input id="OrderID" name="OrderID" value="{{: OrderID}}" disabled="disabled" class="e-field e-ejinputtext valid e-disable"
style="text-align: right; width: 116px; height: 28px" />
</td>
<td style="text-align: right;">
Customer ID
</td>
<td style="text-align: left">
<input id="CustomerID" name="CustomerID" value="{{: CustomerID}}" class="e-field e-ejinputtext valid"
style="width: 116px; height: 28px" />
</td>
</tr>
<tr>
<td style="text-align: right;">
Freight
</td>
<td style="text-align: left">
<input type="text" id="Freight" name="Freight" value="{{:Freight}}" style="text-align: right;" />
</td>
<td style="text-align: right;">
Ship Country
</td>
<td style="text-align: left">
<select id="ShipCountry" name="ShipCountry">
<option value="Argentina">Argentina</option>
<option value="Austria">Austria</option>
<option value="Belgium">Belgium</option>
<option value="Brazil">Brazil</option>
<option value="Canada">Canada</option>
<option value="Denmark">Denmark</option>
<option value="Finland">Finland</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="Ireland">Ireland</option>
<option value="Italy">Italy</option>
<option value="Mexico">Mexico</option>
<option value="Norway">Norway</option>
<option value="Poland">Poland</option>
<option value="Portugal">Portugal</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Switzerland">Switzerland</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="Venezuela">Venezuela</option>
</select>
</td>
</tr>
<tr>
<td style="text-align: right;">
Ship City
</td>
<td style="text-align: left">
<input id="ShipCity" name="ShipCity" value="{{: ShipCity}}" class="e-field e-ejinputtext valid"
style="width: 116px; height: 28px" />
</td>
<td style="text-align: right;">
Verified
</td>
<td style="text-align: left">
<input id="Verified" name="Verified" value="{{:Verified}}" type="checkbox" />
</td>
</tr>
</table>
</script>
  1. Render the Grid control

JS

<div id="Grid"></div>
<script type="text/javascript">
$(function () {// Document is ready.
$("#Grid").ejGrid({
// the datasource "window.gridData" is referred from jsondata.min.js
dataSource: window.gridData,
allowPaging: true,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: ej.Grid.EditMode.DialogTemplate, dialogEditorTemplateID: "#template" },
toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel] },
columns: [
{ field: "OrderID", headerText: "Order ID", isPrimaryKey: true, width: 100 },
{ field: "CustomerID", headerText: "Customer ID", width: 130 },
{ field: "Freight", headerText: "Freight", width: 100, format: "{0:C}" },
{ field: "ShipCity", headerText: "Ship City", width: 100, validationRules: { required: true}, visible: false },
{ field: "ShipCountry", headerText: "Ship Country", width: 100,  },
{ field: "Verified", width: 100, visible: false }//checkbox column
],
actionComplete: "complete",
});
});
</script>
 

MVC

[In View]
@(Html.EJ().Grid<object>("Grid")
.Datasource((IEnumerable<object>)ViewBag.data)
.AllowPaging()
.EditSettings(edit => edit.AllowEditing().AllowAdding().AllowDeleting().EditMode(EditMode.DialogTemplate).DialogEditorTemplateID("#template"))
.ToolbarSettings(toolbar =>
{
toolbar.ShowToolbar().ToolbarItems(items =>
{
items.AddTool(ToolBarItems.Add);
items.AddTool(ToolBarItems.Edit);
items.AddTool(ToolBarItems.Delete);
items.AddTool(ToolBarItems.Update);
items.AddTool(ToolBarItems.Cancel);
});
})
.Columns(col =>
{
col.Field("OrderID").HeaderText("OrderID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(100).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width(100).Add();
col.Field("Freight").Width(100).Format("{0:c2}").Add();
col.Field("ShipCity").HeaderText("Ship City").Width(100).ValidationRules(v => v.AddRule("required", true)).Visible(false).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width(100).Add();
col.Field("Verified").Width(100).Visible(false).Add();
})
.ClientSideEvents(eve=>eve.ActionComplete("complete"))
)
[In controller]
namespace EJGrid.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var DataSource = OrderRepository.GetAllRecords();
ViewBag.data = DataSource;
return View();
}
}
}

ASP.NET

[ASPX]
<ej:Grid ID="OrdersGrid" runat="server" AllowPaging="True" >
<ClientSideEvents ActionComplete="complete" />
<EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" EditMode="DialogTemplate" DialogEditorTemplateID="#template"></EditSettings>
<ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings>
<Columns>
<ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True" />
<ej:Column Field="CustomerID" HeaderText="Customer ID" />
<ej:Column Field="Freight" HeaderText="Freight" Format="{0:C}" />
<ej:Column Field="ShipCity" HeaderText="Ship City" Visible=false>
<ValidationRule>
<ej:KeyValue Key="required" Value="true" />
</ValidationRule>
</ej:Column>
<ej:Column Field="ShipCountry" HeaderText="Ship Country" />
<ej:Column Field="Verified" Visible=false />//checkbox column
</Columns>
</ej:Grid>
[CS]
public partial class _Default : Page
{
List<Orders> order = new List<Orders>();
protected void Page_Load(object sender, EventArgs e)
{
this.OrdersGrid.DataSource = new NorthwindDataContext().Orders;
this.OrdersGrid.DataBind();
}
}
  1. In the actionComplete events of the Grid, the textbox corresponding to the ShipCity label is disabled based on the value of the checkbox.

JS

function complete(args) {
if ((args.requestType == "beginedit" || args.requestType == "add")) {
$("#Freight").ejNumericTextbox({ value: parseFloat($("#Freight").val()), width: "116px", height: "28px", decimalPlaces: 2 });
$("#Freight").css({ 'text-align': 'left' });
if (args.requestType == "add") {
$("#Verified").attr("checked", true);
if ($("#Verified").is(":checked") != true) {//To disable the ShipCity textbox based on checkbox value
$("#ShipCity").attr("disabled", "disabled");
}
}
$("#ShipCountry").ejDropDownList({ width: '116px' });
if (args.requestType == "beginedit") {
$("#OrderID").attr("disabled", "disabled");
$("#ShipCountry").ejDropDownList("setSelectedValue", args.row.children().eq(4).text());
$("#Verified").attr("checked", args.model.currentViewData[args.rowIndex].Verified);
if (args.model.currentViewData[args.rowIndex].Verified != true) {
$("#ShipCity").attr("disabled", "disabled");//To disable the ShipCity textbox based on checkbox value
}
}
}
}
  1. In the change event of the checkbox, when the checkbox state is changed, the error messages are hidden.

JS

$(function (c) {
$(document).on("change", "#Verified", function (c) {
if (c.target.checked != true) {
$("#ShipCity").attr("disabled", "disabled");
$(".e-error").css("display", "none");//to hide the error message when the checkbox state is changed
}
else
$("#ShipCity").removeAttr("disabled");
});
});

 

Conclusion

I hope you enjoyed learning about how to set validation for a column based on another column value in ASP.NET MVC Grid.

You can refer to our ASP.NET MVC Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied