I am using Material Table to display table data. I want to apply validation on surname field. If surname length is less than 3, it should show too small error in red below the input field.
How can this be achieved? The sample code can be found here: https://codesandbox.io/s/misty-breeze-corjj?file=/src/App.tsx
Thanks
{
title: "Surname",
field: "surname",
editComponent: (props: any) => (
<TextField
onChange={props.onChange}
type="number"
helperText={props.helperText}
error={props.error}
variant="standard"
value={props.value}
/>
),
validate: (rowData: any) =>
rowData.surname.length < 3
? { isValid: false, helperText: "too small" }
: true
}
maybe this might help, I think. Try using column.editComponent to override edit component for a column and then using props pass the helperText and error to the TextField. I have used the material-ui v5 TextField here
.
I am using editable option to check the validation. Here I am using onRowUpdate to check the updated data so that we can show the validation message. You can check full example in codesandbox
<MaterialTable
title="Editable Example"
columns={
[
{
title: 'Name', field: 'name',
editComponent: (props) => (
<TextField
type="text"
error={nameError.error}
helperText={nameError.helperText}
value={props.value ? props.value : ''}
onChange={e => props.onChange(e.target.value)}
/>
)
},
{ title: 'Surname', field: 'surname' }
]}
data={state.data}
icons={tableIcons}
editable={{
onRowUpdate: (newData, oldData) =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (newData.name === '' || newData.name.length < 3) {
setNameError({
error: true,
label: 'required',
helperText: 'Name should be more than 3 character'
});
reject();
return;
}
resolve();
if (oldData) {
setState(prevState => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
})
}}
/>