skip to Main Content

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


  1. /^-?d+(?:.d+)?(?:[eE][+-]?d+)?$/
    This would work I think

    Login or Signup to reply.
  2. You could do it in different ways.

    1. Change the input type, like this
    const NumberField = (props) => {
    
      return (
        <TextField
            // your props here
            className="numericInput"
            type="number"
        />
      );
    };
    

    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:

    .numericInput::-webkit-inner-spin-button {
       display: none;
    }
    
    .numericInput::-webkit-outer-spin-button {
       display: none;
    }
    

    Important
    If you haven’t already, you can use css styling with MUI wrapping your App component inside of styled engine, like this:

    <StyledEngineProvider injectFirst>
       <App />
    </StyledEngine>
    

    learn more here https://mui.com/material-ui/guides/interoperability/#css-injection-order

    1. You can create a function that deletes every character that is not accepted, like this:
    const NumberField = (props) => {
      const { errorMessege, ...restProps } = props;
      const { value, setValue } = React.useState();
    
      const numberRegex = /yourregex/gi;
    
      const numberConvertor = (e) => {
        const newValue = e.target.value;
        setValue(newValue.replace(numberRegex, ""));
      };
    
      return (
        <TextField
          fullWidth
          onChange={numberConvertor}
          helperText={errorMessege}
          error={Boolean(errorMessege)}
          {...restProps}
        />
      );
    };
    

    Let me know if any doubt 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search