Home > Enterprise >  How do I write a regular expresssion for phone number that allows number only with plus sign?
How do I write a regular expresssion for phone number that allows number only with plus sign?

Time:11-07

I am writing a simple validation for a phone number text input. I want this text input not to allow any letters and symbols. I only want to allow number and a plus sign at the beginning of the number is optional.

Current code:

$(document).on("input", ".book-appointment-phone", function() {
  let phoneRegex = /[^0-9]/g;
  var digits = this.value.replace(phoneRegex, '');

  return phoneRegex.test(this.value = digits);
});

The current code above can allow numbers only. Do you know how can I update the code above to allow an optional sign at the beginning of the phone number?

For example:

  • 0917678123 - Allowed
  • 9215671234 - Optional sign at the beginning is Allowed

Any help is greatly appreciated. Thank you.

CodePudding user response:

Try this

^[\ \d]?(?:[\d-.\s()]*)$

https://regex101.com/r/npGFhU/1

CodePudding user response:

This code might work for you.

$(document).on("input", ".book-appointment-phone", function() {
  let phoneRegex = /([^0-9\ ])|(?<!^)(\ )/g;
  var digits = this.value.replace(phoneRegex, '');

  return phoneRegex.test(this.value = digits);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="book-appointment-phone">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

^\ ?\d*$

Matches your at the start, then any digit, dash, space, dot, or brackets

you can check it here: http://regex101.com/r/mS9gD7

CodePudding user response:

Try this;

^[\ ]?[\d]*$

In the beginning of the expression, is optional, then variable numbers.

  • Related