darcy111
darcy111

Reputation: 151

HTML input type for phone number

I want to know which type can I use for input phone number.

I can type letters when I do:

<input type="tel" id="phone" name="phone" required>

Also, I want to delete that arrow in right:

<input type="number" id="phone" name="phone" required>

enter image description here

What I want is an input to type only phone number.

Upvotes: 12

Views: 66271

Answers (3)

hamidreza nikoonia
hamidreza nikoonia

Reputation: 2165

All of the above solutions do not avoid the user adding non-number in your input, for example, when you set pattern attribute on <input /> tag, the user can enter non-number char, but when the user submit the form then browser error appear

if you want limit your input just in number , you have to do this with js

Pure Js


const inputValidation = (e) => {
 
    // get value form event
     const value = e.target.value

    // validate value
    const validatedValue = value.replace(/[^0-9]/g, '');

    return validatedValue;


}


React JS


// Implement your input state
const [mobile, setMobile] = React.useState("");


// validate value
const numberHandler = val => {
        const validatedValue = val.replace(/[^0-9]/g, "");
        setMobile(validatedValue);
 };

your input tag


 return (
    <div>
     <input type="tel" value={mobile} onChange={e => numberHandler(e)} />
    </div>

  )

Also, you can show an alert to the user if they enter invalid data


const numberHandler = val => {
        const validatedValue = val.replace(/[^0-9]/g, "");
          
      + // implement alert
      +  if (validatedValue === "" && val !== "") {
      +    alert('you must enter number only')
      +    return
      +  }
        setMobile(validatedValue);
 };

Upvotes: 3

coops
coops

Reputation: 1714

Using tel you can just add some validation to allow only numbers (you can also add a + beforehand and include whatever country code you need).

<form>
  <input type="tel" id="phone" name="phone" pattern="[+]{1}[0-9]{11,14}" required>
  <button>Submit</button>
</form>

This will bring up an error when you submit

Or you can restrict to numbers and hide the arrow by doing this:

.no-arrow {
  -moz-appearance: textfield;
}
.no-arrow::-webkit-inner-spin-button {
  display: none;
}
.no-arrow::-webkit-outer-spin-button,
.no-arrow::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
<form>
  <input id="phone" name="phone" class="no-arrow" value="" type="number">
  <button>Submit</button>
</form>

Upvotes: 19

Ankur Choudhury
Ankur Choudhury

Reputation: 189

If just by removing the arrows solves your problem then you can try including css to disable it:

#phone::-webkit-inner-spin-button, 
#phone::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}

I would suggest using this js library for formatting input fields:

tel input js

Upvotes: 0

Related Questions