Home > Net >  How to read only natural numbers from input
How to read only natural numbers from input

Time:12-09

I have an input to enter a phone number. I need to make it so that the user can enter any characters, for example "fghd6 dhj 3", and only "63" is output to the console. How can I do this? Now I have regular expressions, but it only passes natural numbers, and I need to be able to enter anything and read only natural numbers.

export default class UserPhone extends Component {
  constructor() {
    super();
    this.state = {
      operatorValueState: "",
    };
    this.inputOperatorReference = React.createRef();
    this.operatorValueHandler = this.operatorValueHandler.bind(this);
  }

  operatorValueHandler(e) {
    const regExp = /^[0-9\b] $/;
    if (e.target.value === "" || regExp.test(e.target.value)) {
      this.setState({ operatorValueState: e.target.value });
    }
  }

  componentDidMount() {
    this.inputOperatorReference.current.focus();
  }
  render() {
    return (
      <div>
        <input
          type="text"
          ref={this.inputOperatorReference}
          value={this.state.operatorValueState}
          onInput={this.operatorValueHandler}
        />
      </div>
    );
  }
}

CodePudding user response:

You want to extract numbers from string, if I understand correctly.

Here is how you could do this :

 const handleChange = (event) => {
    const input = event.target.value;

    const numbers = input.match(/\d /g);

    if (numbers && numbers.length > 0) {
      // logic here
    } else {
      // logic here
    }
  };

input.match(/\d /g) will return only numbers

  • Related