Home > Back-end >  Input field that only allows numbers but doesn't allow a single 0 in ReactJS
Input field that only allows numbers but doesn't allow a single 0 in ReactJS

Time:02-13

I need an input form that works with money. You can't type text, symbols, or anything besides numbers but you also shouldn't be able to put $0. It should be $1 and up. When I put /^[0-9\b] $/ it only allows numbers but you can put $0. When I use /^[1-9\b] $/ it doesn't let you put in a zero but if you type 1 and try to put a zero it won't let you. When I try /^[1-9\b] /, it doesn't allow zero but now you can type text and characters. Is there a better way to do this?

const re = /^[0-9\b] $/ is the current regex I'm using.

This is in ReactJS

CodePudding user response:

Try this

<input type="number" min="1" step="any" />

CodePudding user response:

With regex you can use that:
^[^0]\d " And add the rest of your usage, this will avoid 0 being in the begining. [^] match any character that is not in the set - so putting 0 inside will avoid the first char to be 0 (with [^0]).

CodePudding user response:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      financialGoal: ''
    }
  }
  
  handleChange(evt) {
    const financialGoal = (evt.target.validity.valid) ? evt.target.value : this.state.financialGoal;
    
    this.setState({ financialGoal });
  }
  
  render() {
    return (
      <input type="text" pattern="[1-9]*" onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
    )
  }
}
  
ReactDOM.render(<Example />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

  • Related