I currently have a MUI datagrid in which I am validating an email field. The validation works and it does revert back to the original but only if the escape key is pressed. To do this I modified the MUI validation example that they give in which a tooltip will appear if the validation fails.
I want it to revert back to the original if the validation fails and then the cell is clicked out of. I tried using onBlur and stopCellEditMode to accomplish this and clicking outside does now revert it back to the original. The new problem is that it reverts if the email is correct as well. If you remove handleBadEmail the email saves fine. Here is my code:
let promiseTimeout;
const validateEmail = (email) => {
return new Promise((resolve) => {
promiseTimeout = setTimeout(() => {
let emailWorks = false;
if (
//https://stackoverflow.com/questions/46155/how-can-i-validate-an-email-address-in-javascript
String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)
) {
emailWorks = true;
}
resolve(emailWorks ? null : `${email} is not a valid email.`);
}, Math.random() * 500 + 100); // simulate network latency
});
};
const StyledTooltip = styled(({ className, ...props }) => (
<Tooltip {...props} classes={{ popper: className }} />
))(({ theme }) => ({
[`& .${tooltipClasses.tooltip}`]: {
backgroundColor: theme.palette.error.main,
color: theme.palette.error.contrastText,
},
}));
function NameEditInputCell(props) {
const { error, value } = props;
const apiRef = useGridApiContext();
const handleBadEmail = async () => {
let oldValue = apiRef.current.setEditCellValue({
id: props.id,
field: "email",
value: value,
});
if (error) {
apiRef.current.stopCellEditMode({
id: props.id,
field: "email",
value: oldValue,
ignoreModifications: false,
});
}
};
return (
<StyledTooltip open={!!error} title={error}>
<GridEditInputCell onBlur={handleBadEmail} {...props} />
</StyledTooltip>
);
}
function renderEditName(params) {
return <NameEditInputCell {...params} />;
}
const ColDefs = () => {
const preProcessEditCellProps = async (params) => {
const errorMessage = await validateEmail(params.props.value.toString());
return { ...params.props, error: errorMessage };
};
return {
columns: [
{
field: "col1",
headerName: "Seller",
flex: 1,
editable: true,
},
{
field: "email",
headerName: "Email",
flex: 1,
editable: true,
preProcessEditCellProps,
renderEditCell: renderEditName,
},