Text field with only numbers - React

Viewed 73

I am trying to do the text field that will accept only numbers in the format like phone number: xxx-xxx-xxx. I dont want to use the basic thext field format of type="number". Here is my code:

const PatientEditScreen = ({ match }) => {
 const patientId = match.params.id;
 const [phone, setPhone] = useState(0);

useEffect(() => {
    if (!patient.name || patient._id !== patientId) {
      dispatch(listPatientDetails(patientId));
    } else {
      setPhone(patient.phone); 
    }
  }, [dispatch, patientId, patient]);

return (
    <>
      <h1>Edit Patient</h1>
          <Card className="mb-3 border-dark">
            <Card.Body>
              <Form onSubmit={submitHandler}>
                <Form.Row>
                  <Form.Group controlId="phone" as={Col} variant="flush">
                    <Form.Label as="h5">Phone Number</Form.Label>
                    <Form.Control
                      type="number"
                      pattern="[0-9]*"
                      placeholder="Enter Phone Number"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                    ></Form.Control>
                  </Form.Group>
                </Form.Row>
              </Form>
            </Card.Body>
          </Card>
      )}
    </>
  );
};

export default PatientEditScreen;
3 Answers

I had this issue before and found easier option to use because probably there will be bugs in the input field depends on browsers even if it works on one of them fine. I have used directly this github repository which comes with good UI as well. I recommend you to have a look https://gitlab.com/catamphetamine/react-phone-number-input .

this is it:

import React from "react";
import "./style.css";
export default function App() {
  return (
    <div>
      <input
        class="form-control"
        placeholder="xxx"
        type="text"
        maxlength="3"
        pattern="[0-9]{3}"
      />
      -
      <input
        class="form-control"
        placeholder="xxx"
        type="text"
        maxlength="3"
        pattern="[0-9]{3}"
      />
      -
      <input
        class="form-control"
        placeholder="xxx"
        type="text"
        maxlength="3"
        pattern="[0-9]{3}"
      />
    </div>
  );
}

check:https://stackblitz.com/edit/react-q2fjbw?file=src%2FApp.js

You can do something like:

            <Form.Control
              type="number"
              pattern="^[1-9]\d{3}-\d{3}-\d{3}"
              placeholder="Enter Phone Number"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}

Or, if you don't want to use the 'pattern' attribute (or it's not working), you can call a function instead of the setPhone, and validate it there with regex.

Related