I want to prevent users from adding a row with a name that is already in the table, so part of my validation checks that that's the case. But this means that if the user tries to delete a row, they will not be able to save the deletion, since the validation fails. How can I have validation that runs only when the user is creating a row, but skipped when for when the user is deleting a row?
validate: rowData => rowData.name != null && !rowsState.some(x => String(x.name) === String(rowData.name))
You can differentiate between a row that has already been added to the table, compared to a row that is being created, via whether it has a tableData
property. If the tableData
property is undefined, then the row is still being created; otherwise, the row is being edited or deleted.
We can change the code to this:
validate: rowData => rowData.tableData !== undefined || (rowData.requirementId != null && !rowsState.some(x => String(x.requirementId) === String(rowData.requirementId)))
For this table, I only have onRowAdd
and onRowDelete
in the editable
prop of <MaterialTable>
, with no onRowUpdate
. In the case that we want to allow editing a row, it would be more difficult to let the callback of validate
differentiate between editing and deleting a row, as in either scenario the row would have a tableData
property.