How to allow only digits along with decimal on react input

Viewed 5323

i wanted to allow only digits with decimal on react input and do some condition based on the value got, below what i tried which works fine but with problem mentioned below

<FormInput
   name="amount"
   label="Amount"
   onChange: this.handleChange,
   startAdornment: (<InputAdornment position="start">$</InputAdornment>),
   pattern: '[0-9]*',
/>
handleChange = (event) => {
    const { value } = event.target;
    const validValue = Math.abs(parseFloat(value));
    if (validValue && !isNaN(validValue)) {
      // some condition...
      // i have some other set of value that i compare here with input got like if
      // 1) validValue > someValue, then this.setState({ someValue })
      // 2) validValue <= someValue, then this.setState({ validValue })
      // 3) else this.setState({ validValue: 0 })
    }
  }

But the problem here is i am not able to enter decimal along with other digits, like i need to enter 1.2 then first i need to enter 12 and then add '.'(decimal) before 2, so please help me what i can do to allow digits with decimal along other digits

2 Answers

You should not use a pattern for this. You can simply pass type="number" to your input and it will do the validation you desire.

<FormInput
   name="amount"
   label="Amount"
   type="number"
   onChange={this.handleChange}
   startAdornment={<InputAdornment position="start">$</InputAdornment>}
/>

In this case using pattern is not a good solution, you can use type instead of pattern like below,

<FormInput
   type="number"
/>

If you still want to use the pattern, then the pattern you used is not right for the decimal value. You can use the following patter to validate decimal numbers:

^(\d*\.)?\d+$

For decimal with 2 by example:

/^\d+(\.\d{1,2})?$/

Validation

!/^\d+(\.\d{1,2})?$/.test(value.toString())
Related