Steve
Steve

Reputation: 2586

Allowing user to add only space and no more than 11 numbers for phone in textbox

I am trying to set a phone field with following requirements:

I did this which works fine for numbers and spaces but I am not sure how to restrict 11 numbers.

function validatePhone(phone) {
        var filter = /^(?=.*\d)[\d ]+$/;
        if (filter.test(phone)) {
          return phone;
        } else {
          return phone.slice(0,-1);
}

Edit:

I don't want to count all of the entries as 11. I want to count only numbers and not spaces and total numbers should be 11 or 10

Upvotes: 0

Views: 187

Answers (2)

Francesco
Francesco

Reputation: 4250

Here a function that trims the result after the eleventh number, ignoring spaces

function validatePhone(phoneNumber){
  return /( *\d){0,11}/.exec(phoneNumber)[0]
}

console.log(validatePhone('12345671'))
console.log(validatePhone('12345678901'))
console.log(validatePhone('123456789012'))
console.log(validatePhone('1234 56 78   901'))
console.log(validatePhone('123456  7  89012'))

The regex looks for any number of spaces and then a number, at most eleven times and returns the first match.

You have still to handle the starting plus sign and failures (e.g. no match) but this is a starting point

Upvotes: 1

Taplar
Taplar

Reputation: 24965

This proposed solution removes all the spaces and then matches the string against optionally starting with + and then strictly 11 digits.

document.querySelector('#phoneNumber1').addEventListener('input', function(e){
  if (/^\+?\d{11}$/.test(e.target.value.replace(/ /g, ''))) {
    console.log('valid');
  } else {
    console.log('invalid');
  }
});
<input type="text" id="phoneNumber1">

Upvotes: 2

Related Questions