Search code examples
htmlcssbootstrap-5contact-form

Contact number in HTML Form


if we uses "tel" in input then we can give max or min length for the input but its drawback is it may take all kind of inputs whether it is numeric or alphabets,

And if we uses "number" for input then it takes only number but we can not give it min-max characters limit.

Even though I have mentioned pattern inside it but no change. So is there any alternate for the same to give max-min length and can take only numeric?

<div class="form-group">
    <label for="exampleFormControlInput3">Mobile Number</label>
        <div class="input-group">
           <span class="input-group-text" id="basic-addon1">+91</span>
               <input type="tel" class="form-control" id="exampleFormControlInput3" maxlength="10" placeholder="012-345-6789" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
        </div> 
 </div>

enter image description here

Note: I have used bootstrap5 for the same.


Solution

  • You using input type tel and can make a mix with javascript if you want avoid completely alphabetic characters. The type tel provides pattern to but it validate afterwards. And not every browser will supported.

    <label for="phone">Enter your phone number:</label>
    
    <input type="tel" id="phone" name="phone"
           maxlength ="6"
           pattern="[0-9]{3}-[0-9]{3}"
           oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');"
           required>
    
    <small>Format: 123-456</small>

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel