Checking your jQuery phone number allows spaces of at least 8 digits

How can I resolve spaces within the verification of numbers only, with a minimum of 8 digits? Phone numbers are much easier to enter when spaces are allowed. e.g. 0400 123 456, 9699 1234.

Here is my code so far, I only have validation of at least 8 digits:

jQuery.validator.addMethod(
  "phone",
  function(phone_number, element) {
    return this.optional(element) || /^\d{8}$/.test(phone_number);
  },
    "Please enter numbers only"
);
+5
source share
2 answers

Delete the space before checking:

return this.optional(element) || /^\d{8,}$/.test(phone_number.replace(/\s/g, ''));

This way you keep a space

+4
source

My suggestion is to simply remove the spaces from phone_numberbefore checking.

jQuery.validator.addMethod(
  "phone",
  function(phone_number, element) {
    return this.optional(element) || /^\d{8}$/ *$/.test(phone_number.replace(/\s/g, ""));
  },
    "Please enter numbers only"
);
+1
source

All Articles