简体   繁体   中英

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

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. The plus sign 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.

Try this

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

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

^\+?\d*$

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

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

Try this;

^[\+]?[\d]*$

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

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

It doesn't make sense to use the same regex for replace and for test . For replace, the regex should be

/(?!^\+)\D+/g

where \\D is any non-digit character, and (?!^\\+) is a negative lookahead that prevents the \\D matching if it is a + at the start of the string.

 document.querySelector('input').addEventListener('input', function () { let phoneNumber = this.value; // Disallow non-digits. Allow '+' if at start. phoneNumber = phoneNumber.replace(/(?!^\\+)\\D+/g, ''); // Allow, for example, 10 digits maximum. phoneNumber = phoneNumber.replace(/(\\+?\\d{10}).+/, '$1'); this.value = phoneNumber; });
 <input type="text">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM