簡體   English   中英

如何為電話號碼編寫僅允許帶加號的號碼的正則表達式?

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

我正在為電話號碼文本輸入編寫一個簡單的驗證。 我希望這個文本輸入不允許任何字母和符號 我只想在數字的開頭允許數字和加號。 加號是可選的。

當前代碼:

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

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

上面的當前代碼只能允許數字。 您知道如何更新上面的代碼以允許在電話號碼開頭使用可選的+號嗎?

例如:

  • 0917678123 - 允許
  • +9215671234 - 允許在開頭使用可選的 + 符號

任何幫助是極大的贊賞。 謝謝你。

嘗試這個

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

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

^\+?\d*$

匹配開頭的 +,然后匹配任何數字、破折號、空格、點或括號

你可以在這里查看: http : //regex101.com/r/mS9gD7

嘗試這個;

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

在表達式的開頭,+ 是可選的,然后是變量數字。

此代碼可能對您有用。

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

replacetest使用相同的正則表達式是沒有意義的。 對於替換,正則表達式應該是

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

其中\\D是任何非數字字符,並且(?!^\\+)是一個否定的前瞻,如果它是字符串開頭的+ ,它會阻止\\D匹配。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM