Validation

2 Mar 20222 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 by defining the ValidationRules.

@Html.EJS().Grid("Validation").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = "true", minLength=3 }).Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
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.

@Html.EJS().Grid("CustomValid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
   col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width("150").Add();

}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true); }).Load("load").Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

<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();
 }