Validation in Grid Control

26 Oct 20223 minutes to read

Column validation

Column validation allows you to validate the edited or added row data and it display errors for invalid fields before saving data. Grid uses Form Validator component for column validation. You can set validation rules in validationRules property of e-grid-column tag helper.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal" showConfirmDialog="true" showDeleteConfirmDialog="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID"  headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"  validationRules="@(new { required= true })"></e-grid-column>                
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120" validationRules="@(new { required= true, minLength= 3 })"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>                               
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>                
    </e-grid-columns>
 </ejs-grid>
public IActionResult Index()
 {
   var orders = OrderDetails.GetAllRecords();
   ViewBag.DataSource = orders;            
   return View();
 }

Custom validation

You can define your own custom validation rules for the specific columns by using Form Validator custom rules.

In the below demo, custom validation applied for CustomerID column.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })" load="load">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100" validationRules="@(new{ required = true })"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>

    function load(args) {
        this.columns[1].validationRules = { required: true, minLength: [customFn, 'Need atleast 5 letters'] };
    }
    
    function customFn(args) {
        return args['value'].length >= 5;
    };

</script>
public IActionResult Index()
 {
   ViewBag.DataSource = OrdersDetails.GetAllRecords();            
   return View();
 }