make sure first three digits of phone number are not 0’s, using javascript
我正在尝试使用 javascript 验证电话号码,但我被困在这部分
区号(999中的前3位数字)不能全为零(0)的
我知道生成我想要的任何格式的代码(比如 xxx-xxx-xxxx),但是我如何确保第一个 0 不是全为零?
感谢任何帮助,谢谢!
- var isValid = !/^000/.test(str);
您可以通过多种方式做到这一点,这里有几个使用不同方法的示例。
使用startsWith
1
2 3 4 5 |
var num =“000-xxx-xxxx”;
if (num.startsWith(“000”) === true) { |
使用 substr
1
2 3 4 5 6 |
var num =“000-xxx-xxxx”;
var first_three = num.substr(0, 3); if (first_three ===“000”) { |
使用拆分
1
2 3 4 5 6 |
var num =“000-xxx-xxxx”;
var first_three = num.split(“-“)[0]; if (first_three ===“000”) { |
使用正则表达式
1
2 3 4 5 |
var num =“000-xxx-xxxx”;
if (/^000/.test(num)) { |
假设您正在测试美国区号,使用正则表达式
/^[2-9][0-8][0-9]/ 来测试它们应该可以工作。根据
这。
区号可以以 2 到 9 之间的数字开头,第二个数字可以是任何
除 9 以外的数字,最后一个数字可以是任意数字。
1
2 3 4 |
function hasValidAreaCode(num) {
var stripped = num.replace(/\\D/g, ”); // remove any no-numeric characters return /^[2-9][0-8][0-9]/.test(stripped); } |
交互示例:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function hasValidAreaCode(num) {
var stripped = num.replace(/\\D/g, ”); // remove any no-numeric characters return /^[2-9][0-8][0-9]/.test(stripped); } var elPhonenumber = document.getElementById(‘phonenumber’); var v = elPhonenumber.value; |
1
2 3 4 5 6 7 8 9 |
.valid, .invalid {
color: #000; } .valid { color: green; } .invalid { color: red; } |
1
|
<label for=“phonenumber”>Please enter a phonenumber</label> <input id=“phonenumber”>
|
您可以使用 ^[0]{3}$ 或 ^\\d{3}$
你可以使用parseInt,它会忽略字符串中第一个非数字字符之后的所有内容:
1
2 3 4 5 6 7 8 9 |
var phone1 = ‘000-555-4444’;
var phone2 = ‘555-555-5555’; function isValidAreaCode(phoneNumber) { console.log(phone1, ‘valid?’, isValidAreaCode(phone1)); |
来源:https://www.codenong.com/43289775/