Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html input type for phone number

Tags:

html

css

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.

like image 254
darcy111 Avatar asked Apr 02 '19 10:04

darcy111


2 Answers

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>
like image 124
coops Avatar answered Sep 21 '22 07:09

coops


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);
 };

like image 36
hamidreza nikoonia Avatar answered Sep 19 '22 07:09

hamidreza nikoonia