Validating whether an email ID already exists is a common requirement in web development. In this guide, we'll show you how to implement this validation in a jqGrid using a custom function.
Step 1: Define the Grid Column
First, define the column for the email ID in your jqGrid. Add the custom
validation rule and specify the custom function:
colModel: [
{
name: 'emailId',
index: 'emailId',
width: 200,
editable: true,
sorttype: 'int',
editrules: {
email: true,
required: true,
custom: true,
custom_func: checkvalid
}
}
]
Step 2: Implement the Custom Validation Function
Next, implement the checkvalid
function to check if the email ID already exists:
function checkvalid(value, colname) {
var gr = jQuery("#list2").getGridParam('selarrrow');
if (gr == '') {
var flag = false;
var allRowsInGrid = $("#list2").getGridParam("records");
for (i = 1; i <= allRowsInGrid; i++) {
var rowId = $("#list2").getRowData(i);
var emailId = rowId['emailId'];
if (emailId == value) {
flag = true;
}
}
if (flag == true) {
return [false, "Email Id: Email already exists, please enter a different email ID."];
} else {
return [true, ""];
}
} else {
return [true, ""];
}
}
Step 3: Explanation of the Code
Let's break down the checkvalid
function:
- gr: Gets the selected rows in the grid.
- If no rows are selected, it iterates through all rows in the grid.
- Compares each email ID in the grid with the provided
value
. - If a match is found, it sets the
flag
to true. - If the flag is true, it returns an error message. Otherwise, it returns true.
Conclusion
By following these steps, you can implement a custom validation function in jqGrid to check if an email ID already exists. This helps ensure data integrity and prevents duplicate entries.
Comments
Post a Comment