Skip to content

Need to add Custom validation for particular column externally topic … #4138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: hotfix/hotfix-v29.1.33
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
public IActionResult Index()
{
ViewBag.DataSource = OrderDetails.GetAllRecords();
return View();
}
112 changes: 112 additions & 0 deletions ej2-asp-core-mvc/code-snippet/grid/edit/custom-validation/razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<div class="control-section" style="display: flex;">
<div class="col-lg-3 property-section" style="margin-right: 20px;">
<table style="width: 100%;">
<tr>
<td style="padding-top: 10px;">Column Fields</td>
<td>
@Html.EJS().DropDownList("columnFields").Placeholder("Select field").Render()
</td>
</tr>
<tr>
<td style="padding-top: 15px;">Enable Custom Validation</td>
<td>
@Html.EJS().CheckBox("customValidationCheckbox").Disabled(true).Render()
</td>
</tr>
</table>
</div>
</div>
<div class="col-md-8">
@Html.EJS().Grid("grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowPaging(true).PageSettings(p => p.PageCount(5)).Toolbar(new List<string> { "Add", "Edit", "Delete", "Update", "Cancel" }).EditSettings(edit => edit.AllowEditing(true).AllowAdding(true).AllowDeleting(true).ShowAddNewRow(true)).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").IsPrimaryKey(true).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = true, number = true }).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("120").ValidationRules(new { required = true, minLength = 5 }).Add();
col.Field("Freight").HeaderText("Freight").Width("180").Format("C2").EditType("numericedit").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = true, min = 0 }).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").EditType("datetimepickeredit").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format(new { type = "dateTime", format = "M/d/y hh:mm a" }).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").EditType("dropdownedit").Edit(new { @params = new { popupHeight = 300 } }).Add();
}).ActionBegin("actionBegin").Render()
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
var dropdownObj = document.getElementById('columnFields').ej2_instances[0];
var checkboxObj = document.getElementById('customValidationCheckbox').ej2_instances[0];
var gridObj = document.getElementById('grid').ej2_instances[0];

let columnsConfig = [
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'Customer ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'OrderDate', headerText: 'Order Date' },
{ field: 'ShipCountry', headerText: 'Ship Country' }
];

dropdownObj.dataSource = columnsConfig.map(c => ({ text: c.headerText, value: c.field }));
dropdownObj.fields = { text: 'text', value: 'value' };
dropdownObj.dataBind();

let selectedField = null;

dropdownObj.addEventListener('change', function (e) {
selectedField = e.value;
checkboxObj.disabled = false;

if (checkboxObj.checked) {
addValidation(selectedField); // Apply validation if checkbox is already checked.
}
});

checkboxObj.addEventListener('change', function (e) {
if (!selectedField) return;

if (e.checked) {
addValidation(selectedField);
} else {
resetValidation(selectedField);
}
});

function actionBegin(args) {
if (args.requestType === 'save') {
// Add logic if needed for save request.
}
}

//Apply custom validation to the selected column.
function addValidation(field) {
gridObj.columns.forEach(col => {
if (col.field === field) {
col.validationRules = {
required: [customFn, 'Custom required rule applied for this field.']
};
gridObj.editModule?.formObj?.addRules(field, col.validationRules);
} else if (col.isPrimaryKey) {
col.validationRules = { required: true };
gridObj.editModule?.formObj?.addRules(col.field, col.validationRules);
} else {
col.validationRules = null;
gridObj.editModule?.formObj?.removeRules(col.field);
}
});

gridObj.editModule?.formObj && gridObj.closeEdit();
}

function resetValidation(field) {
let col = gridObj.getColumnByField(field);
if (col.isPrimaryKey) {
col.validationRules = { required: true };
gridObj.editModule?.formObj?.addRules(col.field, col.validationRules);
} else {
col.validationRules = null;
gridObj.editModule?.formObj?.removeRules(col.field);
}

gridObj.editModule?.formObj && gridObj.closeEdit();
}

function customFn(args) {
return args.value !== '' && args.value !== undefined;
}
});
</script>
116 changes: 116 additions & 0 deletions ej2-asp-core-mvc/code-snippet/grid/edit/custom-validation/tagHelper
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<div class="control-section" style="display: flex;">
<div class="col-lg-3 property-section" style="margin-right: 20px;">
<table style="width: 100%;">
<tr>
<td style="padding-top: 10px;">Column Fields</td>
<td>
<ejs-dropdownlist id="columnFields" placeholder="Select field"></ejs-dropdownlist>
</td>
</tr>
<tr>
<td style="padding-top: 15px;">Enable Custom Validation</td>
<td>
<ejs-checkbox id="customValidationCheckbox" disabled="true"></ejs-checkbox>
</td>
</tr>
</table>
</div>

<div class="col-md-8">
<ejs-grid id="grid" dataSource="@ViewBag.DataSource" actionBegin="actionBegin" allowPaging="true" toolbar="@(new List<string> { "Add", "Edit", "Delete", "Update", "Cancel" })">
<e-grid-pagesettings pageCount="5"></e-grid-pagesettings>
<e-grid-editsettings allowEditing="true" allowAdding="true" allowDeleting="true" showAddNewRow="true"></e-grid-editsettings>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" width="120" isPrimaryKey="true" textAlign="Right" validationRules="@(new { required = true, number = true })"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer ID" width="120" validationRules="@(new { required = true, minLength = 5 })"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" width="180" format="C2" editType="numericedit" textAlign="Right" validationRules="@(new { required = true, min = 0 })"></e-grid-column>
<e-grid-column field="OrderDate" headerText="Order Date" width="130" editType="datetimepickeredit" textAlign="Right" format="@(new { type = "dateTime", format = "M/d/y hh:mm a" })"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="Ship Country" width="150" editType="dropdownedit" edit="@(new { @params = new { popupHeight = 300 } })"></e-grid-column>
</e-grid-columns>
</ejs-grid>
</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
var dropdownObj = document.getElementById('columnFields').ej2_instances[0];
var checkboxObj = document.getElementById('customValidationCheckbox').ej2_instances[0];
var gridObj = document.getElementById('grid').ej2_instances[0];

let columnsConfig = [
{ field: 'OrderID', headerText: 'Order ID' },
{ field: 'CustomerID', headerText: 'Customer ID' },
{ field: 'Freight', headerText: 'Freight' },
{ field: 'OrderDate', headerText: 'Order Date' },
{ field: 'ShipCountry', headerText: 'Ship Country' }
];

dropdownObj.dataSource = columnsConfig.map(c => ({ text: c.headerText, value: c.field }));
dropdownObj.fields = { text: 'text', value: 'value' };
dropdownObj.dataBind();

let selectedField = null;

dropdownObj.addEventListener('change', function (e) {
selectedField = e.value;
checkboxObj.disabled = false;

if (checkboxObj.checked) {
addValidation(selectedField); // Apply validation if checkbox is already checked.
}
});

checkboxObj.addEventListener('change', function (e) {
if (!selectedField) return;

if (e.checked) {
addValidation(selectedField);
} else {
resetValidation(selectedField);
}
});

function actionBegin(args) {
if (args.requestType === 'save') {
// Add logic if needed for save request.
}
}

//Apply custom validation to the selected column.
function addValidation(field) {
gridObj.columns.forEach(col => {
if (col.field === field) {
col.validationRules = {
required: [customFn, 'Custom required rule applied for this field.']
};
gridObj.editModule?.formObj?.addRules(field, col.validationRules);
} else if (col.isPrimaryKey) {
col.validationRules = { required: true };
gridObj.editModule?.formObj?.addRules(col.field, col.validationRules);
} else {
col.validationRules = null;
gridObj.editModule?.formObj?.removeRules(col.field);
}
});

gridObj.editModule?.formObj && gridObj.closeEdit();
}

function resetValidation(field) {
let col = gridObj.getColumnByField(field);
if (col.isPrimaryKey) {
col.validationRules = { required: true };
gridObj.editModule?.formObj?.addRules(col.field, col.validationRules);
} else {
col.validationRules = null;
gridObj.editModule?.formObj?.removeRules(col.field);
}

gridObj.editModule?.formObj && gridObj.closeEdit();
}

function customFn(args) {
return args.value !== '' && args.value !== undefined;
}
});
</script>
25 changes: 0 additions & 25 deletions ej2-asp-core-mvc/grid/EJ2_ASP.MVC/editing/edit.md
Original file line number Diff line number Diff line change
@@ -192,31 +192,6 @@ In the following code example, the Employee Name is a foreign key column. When e
| -------------- | ------------- |
| ![Foreign key column edit](../images/editing/on-foreign-key-column-editing.png) | ![After foreign key column edit](../images/editing/after-foreign-key-column-editing.png) |

## Prevent adding duplicate rows in Syncfusion ASP.NET MVC Grid with custom validation

The Syncfusion ASP.NET MVC Grid allows you to enforce constraints to prevent duplicate rows by customizing the validation logic within the Grid setup. This ensures data integrity by restricting duplicate entries in the **OrderID** column.

To prevent adding duplicate rows in the Grid, follow these steps:

1. Implement Custom Validation: Define the `orderIdCustomValidation` function to check whether the entered **OrderID** already exists in the [DataSource](https://help.syncfusion.com/cr/aspnetmvc-js2/Syncfusion.EJ2.Grids.Grid.html#Syncfusion_EJ2_Grids_Grid_DataSource). This allows editing an existing row without triggering a duplicate error.

2. Add Dynamic Validation Rules: Create the `orderIDRules` object to enforce unique **OrderID** values. Dynamically add this rule to the form during the **save** action.

3. Handle Validation in the [ActionBegin](https://help.syncfusion.com/cr/aspnetmvc-js2/syncfusion.ej2.grids.grid.html#Syncfusion_EJ2_Grids_Grid_ActionBegin) event: In the `ActionBegin` event, check if the **requestType** is **save**. Apply the validation rule before saving and cancel the action `args.cancel = true` if the validation fails.

For server-side validation to prevent adding duplicate rows, you can refer to the detailed guidance provided in our [knowledge base](https://support.syncfusion.com/kb/article/11608/how-to-do-server-side-validation-for-grid-in-asp-net-mvc-application). If you want to display the Grid's validation tooltip instead of the alert used in our knowledge base, you can call the `grid.editModule.formObj.validate()` method in the `Ajax/Fetch` success function to display the Grid's tooltip validation for the server side.

{% tabs %}
{% highlight razor tabtitle="CSHTML" %}
{% include code-snippet/grid/edit/prevent-add-duplicate/razor %}
{% endhighlight %}
{% highlight c# tabtitle="Edit-temp.cs" %}
{% include code-snippet/grid/edit/prevent-add-duplicate/customvalidation.cs %}
{% endhighlight %}
{% endtabs %}

![Prevent Duplicate row](../images/editing/prevent-duplicate-row.png)

## How to perform CRUD action externally

Performing CRUD (Create, Read, Update, Delete) actions externally in the Syncfusion<sup style="font-size:70%">&reg;</sup> Grid allows you to manipulate grid data outside the grid itself. This can be useful in scenarios where you want to manage data operations programmatically.
60 changes: 59 additions & 1 deletion ej2-asp-core-mvc/grid/EJ2_ASP.MVC/editing/validation.md
Original file line number Diff line number Diff line change
@@ -80,6 +80,39 @@ In the following example, custom validation functions, namely **customFunction**

![Custom validation for numeric column](../images/editing/validation-numeric.png)

### Custom validation for particular column externally

In Syncfusion ASP.NET MVC Grid, you can dynamically apply custom validation rules to specific columns using external UI elements such as a **DropdownList** and a **Checkbox**.

To achieve this follow these steps:

1. Define the **columnsConfig** array with fields, validation rules, and edit types and assign **columnsConfig** to the `grid.columns` property.

2. Use a DropdownList to select the target column and a Checkbox to enable or disable custom validation.

3. When the Checkbox is checked, call the private `addValidation()` method to apply the custom validation rule and retrieve the selected column and update its `ValidationRules` with a custom function.

4. Use `formObj.addRules()` to apply rules and `formObj.removeRules()` to reset them dynamically.

5. Always apply the default required rule to the primary key **OrderID** regardless of the custom selection.

6. Use the [ActionBegin](https://help.syncfusion.com/cr/aspnetmvc-js2/syncfusion.ej2.grids.grid.html#Syncfusion_EJ2_Grids_Grid_ActionBegin) method to manage validation before saving data.

These custom validation rules can be linked to specific columns using the `ValidationRules` property. The rules can be defined externally as functions and applied dynamically to the corresponding column settings in the Grid. By default, the default validation rules will be applied to the columns. Upon enabling the Custom Validation from checkbox, the custom validation will be applied.

The following example demonstrates how to apply dynamically enable and disable validation using `ValidationRules` property.

{% tabs %}
{% highlight razor tabtitle="CSHTML" %}
{% include code-snippet/grid/edit/custom-validation/razor %}
{% endhighlight %}
{% highlight c# tabtitle="columnvalid.cs" %}
{% include code-snippet/grid/edit/custom-validation/custom-validation.cs %}
{% endhighlight %}
{% endtabs %}

![Custom validation for particular column externally](../images/editing/custom-validation.gif)

## Dynamically add or remove validation rules from the form

You can dynamically add or remove validation rules from input elements within a form. This feature is particularly useful when you need to adjust the validation rules based on different scenarios or dynamically changing data.
@@ -333,4 +366,29 @@ namespace UrlAdaptor.Controllers
{% endhighlight %}
{% endtabs %}

![Show custom error message](../images/editing/custom-message.png)
![Show custom error message](../images/editing/custom-message.png)

## Prevent adding duplicate rows with custom validation

The Syncfusion ASP.NET MVC Grid allows you to enforce constraints to prevent duplicate rows by customizing the validation logic within the Grid setup. This ensures data integrity by restricting duplicate entries in the **OrderID** column.

To prevent adding duplicate rows in the Grid, follow these steps:

1. Implement Custom Validation: Define the `orderIdCustomValidation` function to check whether the entered **OrderID** already exists in the [DataSource](https://help.syncfusion.com/cr/aspnetmvc-js2/Syncfusion.EJ2.Grids.Grid.html#Syncfusion_EJ2_Grids_Grid_DataSource). This allows editing an existing row without triggering a duplicate error.

2. Add Dynamic Validation Rules: Create the `orderIDRules` object to enforce unique **OrderID** values. Dynamically add this rule to the form during the **save** action.

3. Handle Validation in the [ActionBegin](https://help.syncfusion.com/cr/aspnetmvc-js2/syncfusion.ej2.grids.grid.html#Syncfusion_EJ2_Grids_Grid_ActionBegin) event: In the `ActionBegin` event, check if the **requestType** is **save**. Apply the validation rule before saving and cancel the action `args.cancel = true` if the validation fails.

For server-side validation to prevent adding duplicate rows, you can refer to the detailed guidance provided in our [knowledge base](https://support.syncfusion.com/kb/article/11608/how-to-do-server-side-validation-for-grid-in-asp-net-mvc-application). If you want to display the Grid's validation tooltip instead of the alert used in our knowledge base, you can call the `grid.editModule.formObj.validate()` method in the `Ajax/Fetch` success function to display the Grid's tooltip validation for the server side.

{% tabs %}
{% highlight razor tabtitle="CSHTML" %}
{% include code-snippet/grid/edit/prevent-add-duplicate/razor %}
{% endhighlight %}
{% highlight c# tabtitle="Edit-temp.cs" %}
{% include code-snippet/grid/edit/prevent-add-duplicate/customvalidation.cs %}
{% endhighlight %}
{% endtabs %}

![Prevent Duplicate row](../images/editing/prevent-duplicate-row.png)
Loading