1

How to restrict my text box to only numbers with minimum length to 10 and another version like accept + at the start and after two & three & numbers - should come..like +91-123-456-7890

Here is my code

<input type="text" maxlength="10" onkeyup="if (/\D/g.test(this.value)) 
this.value = this.value.replace(/\D/g,'')" name="mobile" placeholder="Mobile Number">    
Cœur
  • 37,241
  • 25
  • 195
  • 267
kishore
  • 356
  • 1
  • 3
  • 20
  • Whats the +number for if you're restricting it to 2 numbers, country codes have 1 to 3 numbers(e.g 1 for US and Canada, or 353 for ROI)? – Nick is tired Apr 19 '17 at 16:04

3 Answers3

3

Use this code

<input type="text" name="mobile" pattern="[1-9]{1}[0-9]{9}" title="Enter 10 digits"> 
Bhupesh
  • 883
  • 7
  • 16
  • its not working @bhupesh, from my code i'm able to restrict user entering alphabets but need to make it minimum length to 10 ofcourse i made the max length to 10 – kishore Apr 19 '17 at 06:31
  • 1
    refer this link http://stackoverflow.com/questions/19611599/html5-phone-number-validation-with-pattern – Bhupesh Apr 19 '17 at 06:40
  • Good use of the `pattern` attribute. – Rounin Apr 19 '17 at 14:22
0

Here is one approach using library-less javascript (rather than jQuery):

var numberInputs = document.getElementsByClassName('tel');
var paragraph = document.querySelector('form p');

function checkInput(i) {
    var input = numberInputs[i];
    var inputLength = input.value.length;
    var inputMax = parseInt(numberInputs[i].getAttribute('maxlength'));
    
    if ((inputLength > 0) && (!input.value[(inputLength - 1)].match(/\d/))) {

    input.value = input.value.substring(0, (inputLength - 1));
    inputLength = input.value.length;
    input.style.borderColor = 'rgb(255, 0, 0)';
    paragraph.textContent = 'Please write only numbers';
    paragraph.style.color = 'rgb(255, 0, 0)';

    }

    else {
        input.removeAttribute('style');
        paragraph.textContent = '';
    }

    if (inputLength === inputMax) {
    
        if (i < (numberInputs.length - 1)) {
            numberInputs[(i+1)].focus();    
        }

        else {
            paragraph.textContent = 'Your number is: +' + numberInputs[0].value;
    
            for (var j = 1; j < numberInputs.length; j++) {
                paragraph.textContent += '-' + numberInputs[j].value;
            }

            paragraph.style.color = 'rgb(0, 0, 255)';   
        }
    }
}

for (let i = 0; i < numberInputs.length; i++) {
    numberInputs[i].addEventListener('keyup', function(){checkInput(i);}, false);
}
<form>
+
<input class="tel" type="text" size="2" maxlength="2" />
-
<input class="tel" type="text" size="3" maxlength="3" />
-
<input class="tel" type="text" size="3" maxlength="3" />
-
<input class="tel" type="text" size="4" maxlength="4" />
<p></p>
</form>
Rounin
  • 27,134
  • 9
  • 83
  • 108
0

Use this code

<input type=“number” oninput=“slice(0,10)”>