kishore
kishore

Reputation: 386

Restricting input text to only numbers and with minimum length to 10 for phone number

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">    

Upvotes: 1

Views: 1461

Answers (3)

user8841976
user8841976

Reputation:

Use this code

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

Upvotes: 0

Rounin
Rounin

Reputation: 29493

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>

Upvotes: 0

Bhupesh
Bhupesh

Reputation: 881

Use this code

<input type="text" name="mobile" pattern="[1-9]{1}[0-9]{9}" title="Enter 10 digits"> 

Upvotes: 3

Related Questions