How to modifiy Material-UI TextField input type Number
for now the type = "number"
in TextFiled Material-UI
accept number(0-9)
coma (,)
and double dash(--)
and, I just need one dash(-)
I've seen to insert pattern in inputProps, but it seems not working..
Any help is greatly appreciated
Thank you
<TextField
label="Super Koin"
variant="outlined"
type="number"
inputProps={{
pattern: /^-?\d+(?:\.\d+)?$/g
}}
name="Gajian"
style={{ marginBottom: "22px" }}
defaultValue={
(form.injectCustomer && form.injectCustomer.supercoin) ||
0
}
fullWidth
inputRef={this.superPoints}
InputLabelProps={{
shrink: true
}}
onChange={e => {
this.actionRow(
{ key: "supercoin", value: (e.target.value)},
"supercoin"
);
}}
/>
I'm trying to make validation inside onChange
onChange={e => {
console.log(e.target.value,"EEE")
this.actionRow({
key: "supercoin",
value: e.target.value === "--" ? e.target.value = 0 : e.target.value =
},
"supercoin"
);
}}
but, the console.log for "-" and "--" is empty and it seems impossible to validate from onChange
Solution 1:
You could use react-number-format and provide a custom implementation of the <input>
element with the inputComponent
property:
import React from "react";
import PropTypes from "prop-types";
import NumberFormat from "react-number-format";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
const NumberFormatCustom = React.forwardRef(function NumberFormatCustom(props, ref) {
const { onChange, ...other } = props;
return (
<NumberFormat
{...other}
getInputRef={ref}
onValueChange={(values) => {
onChange({
target: {
name: props.name,
value: values.value,
},
});
}}
// isNumericString
/>
);
});
NumberFormatCustom.propTypes = {
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
export default function FormattedInput() {
const [numberformat, setNumberformat] = React.useState(0);
const handleChange = (event) => {
setNumberformat(event.target.value);
};
return (
<Box>
<TextField
label="react-number-format"
value={numberformat}
onChange={handleChange}
name="numberformat"
id="formatted-numberformat-input"
InputProps={{
inputComponent: NumberFormatCustom,
}}
variant="standard"
/>
</Box>
);
}
Solution 2:
I think when using patterns you have to use the type="text"
.
Then add the inputMode: 'numeric'
in your inputProps
.
<TextField
type="text"
inputProps={{
inputMode: 'numeric',
pattern: '/^-?\d+(?:\.\d+)?$/g'
}}
/>