Home > front end >  Phone number validation in React JS - how to limit type and length of input?
Phone number validation in React JS - how to limit type and length of input?

Time:10-15

I am trying to do a simple input form which only accepts numbers with a total length of 10 characters.

I am using the maxLength attribute in my JSX to limit input length:

<FormControl input type="tel" maxLength="10" onKeyDown={(e)=> checkInput(e)} />

And here is the function where I check if the key is allowed (digits and backspace keys only)

const [number, setNumber] = useState()

const checkInput = (e) =>{
    if(!(e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode === 8)){
        e.preventDefault()
    }
    else{
        setNumber(e.target.value)
    }
   
}

This works fine except for the state which is always one keystroke behind due to the keyDown e.listener.

I also tried using the type="number" attribute in my JSX but this does not work in conjunction with max=9999999999 neither with maxLength=10 attributes

CodePudding user response:

Properly duplicate: e.target.value shows values one key 'behind'

Solution with onChange:

import React from "react";
import { useState } from "react";
import { FormControl } from "react-bootstrap";

const App = () => {
  const [number, setNumber] = useState("");

  const checkInput = (e) => {
    const onlyDigits = e.target.value.replace(/\D/g, "");
    setNumber(onlyDigits);
  };

  console.log({ number });
  return (
    <div>
      <FormControl
        type="tel"
        maxLength="10"
        value={number}
        onChange={(e) => checkInput(e)}
      />
    </div>
  );
};

export default App;
  • Related