I want to make validation for numbers with scientific notation (‘e’, ‘+’, ‘-‘, ‘.’) using regex i tried some of but that’s not working
like
Regular Numbers
/^(0|[1-9]d*)(e-?(0|[1-9]d*))?$/i
Whole positive and negative number regex validation, supports numbers like -6e4, -16e-10, -0e0 but also regular numbers like -0, -11, and all the entire positive numbers above:
/^-?(0|[1-9]d*)(e-?(0|[1-9]d*))?$/i
const NumberField = (props) => {
const { errorMessege, ...restProps } = props;
const Number = /^-?(0|[1-9]d*)(e-?(0|[1-9]d*))?$/i;
const numberConvertor = (e) => {
if (e.target.value == '' || Number.test(e.target.value)) {
// this.setState({and_: e.target.value})}
console.log(e.target.value);
} else {
e.preventDefault();
// return false;
}
};
return (
<TextField
fullWidth
onKeyPress={numberConvertor}
helperText={errorMessege}
error={Boolean(errorMessege)}
{...restProps}
/>
);
};
2
Answers
/^-?d+(?:.d+)?(?:[eE][+-]?d+)?$/
This would work I think
You could do it in different ways.
This will accept "e" character too, so you can use exponential. Also you can remove the ugly number selector (the arrows next to the input) in css like this:
Important
If you haven’t already, you can use css styling with MUI wrapping your App component inside of styled engine, like this:
learn more here https://mui.com/material-ui/guides/interoperability/#css-injection-order
Let me know if any doubt 🙂