JavaScript Coder

JavaScript Form Validation - Phone Numbers

javascript form validation phone number validation html form validation

The easiest way to validate phone numbers using Javascript would be to use Regular expressions.

However there are different formats of Phone numbers depending on the user’s preference.

Here are some regular expressions to validate phone numbers

Phone number validation using a simple Regular expression

function validatePhoneNumber(input_str) 
{
    var re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;

    return re.test(input_str);
}

This function will allow phone numbers entered in the formats like this

  • (123) 456-7890
  • (123)456-7890
  • 123-456-7890
  • 1234567890

Try the working demo

HTML5 tel input with pattern validation

A much modern way to get phone number input from the user is to use the tel input type. The other advantage is that mobile phone browsers can optimize the input field by displaying a keyboard suitable for entering phone numbers.

<input type="tel" id="phone" name="phone"
       pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
       required>

Note that the pattern attribute takes a regular expression that will be used to validate the input.

This will validate; However, if you want to display a custom error message, you will have to add a little custom Javascript

var phone_input = document.getElementById("myform_phone");

phone_input.addEventListener('input', () => {
  phone_input.setCustomValidity('');
  phone_input.checkValidity();
});

phone_input.addEventListener('invalid', () => {
  if(phone_input.value === '') {
    phone_input.setCustomValidity('Enter phone number!');
  } else {
    phone_input.setCustomValidity('Enter phone number in this format: 123-456-7890');
  }
});

Should you go too hard on validations?

Remember, too hard validations can go against good usability and can irritate your users. Validation is only to help users fix obvious mistakes. So prefer simple validations (for example, just check there are 10 digits)

function validatePhone(input_phone)
{
    return(input_phone.replace(/\D/g,'').length == 10)
}

References

See Also