I am using material table cellEditable in my project and I want to override cell component to restrict users from entering negative no in the field. also, throw error validation. I am able to achieve that in "editable" but not on cellEditable How to achieve that??
https://codesandbox.io/s/material-demo-forked-h1f8d?file=/demo.js:609-979
<MaterialTable
title="Cell Editable Preview"
columns={columns}
data={data}
cellEditable={{
onCellEditApproved: (newValue, oldValue, rowData, columnDef) => {
return new Promise((resolve, reject) => {
console.log("newValue: " + newValue);
setTimeout(resolve, 1000);
});
}
}}
/>
I haven't been able to find how to restrict even an entry of a negative number, but I have been able to restrict saving it. Also this will throw an alert letting you know you're trying to save a negative number into the Year field.
onCellEditApproved: (newValue, oldValue, rowData, columnDef) => {
return new Promise((resolve, reject) => {
if (columnDef.field === "birthYear" && newValue < 0) {
alert("You entered a negative year....");
return reject();
}
setData((prev) =>
prev.map((item, i) => {
if (rowData.tableData.id === i)
item[columnDef.field] = newValue;
return item;
})
);
setTimeout(resolve(), 1000);
});
Note that this code will allow you to successfully update all other fields as well.
Sandbox: https://codesandbox.io/s/material-demo-forked-x74m1?file=/demo.js