简体   繁体   English

在不使用正则表达式的情况下验证具有不同格式的电话号码

[英]Validating phone number with different formats WITHOUT regex

In JavaScript, I need validate phone numbers without using regular expressions (must be with string manipulation). 在JavaScript中,我需要在不使用正则表达式的情况下验证电话号码(必须使用字符串操作)。 The phone numbers have to be in one of the following formats: 电话号码必须采用以下格式之一:

  1. 123-456-7890 123-456-7890
  2. 1234567890 1234567890
  3. (123)4567890 (123)4567890
  4. (123)456-7890 (123)456-7890

Then I must also provide an alert if the phone number isn't in one of the formats listed above. 然后,如果电话号码不是上面列出的格式之一,我还必须提供警报。

I have only been able to manage to get #2 working, which looks something like this: 我只能设法使#2正常工作,看起来像这样:

function len(gth) 
{
if (gth.value.length != 10) 
    {
        alert("Telephone numbers MUST be 10 digits!");
    }
}

which down in the HTML it would call up to the function: 在HTML中它会调用该函数:

<p>Phone: &nbsp;&nbsp; <input id = "phone" onblur="len(this)" name = "Phone" size = "20" type = "text" maxlength = "10"> </p>

Since you need a solution without regex, I believe this should work. 由于您需要不使用正则表达式的解决方案,因此我认为这应该可行。

 const phones = [ '123-456-7890', '1234567890', '(123)4567890', '(123)456-7890', '+61(123) 456-7890', '12345', '))))01/34$89.77(99' ] function len(gth) { if (gth.substring(3, 4) == '-' && gth.substring(7, 8) == '-') // 123-456-7890 gth = gth.replace('-', '').replace('-', ''); else if (gth.substring(0, 1) == '(' && gth.substring(4, 5) == ')' && gth.substring(8, 9) == '-') // (123)456-7890 gth = gth.replace('(', '').replace(')', '').replace('-', ''); else if (gth.substring(0, 1) == '(' && gth.substring(4, 5) == ')') // (123)4567890 gth = gth.replace('(', '').replace(')', ''); if (!isNaN(gth) && gth.length == 10) { return true; } alert("Telephone numbers:" + gth + " MUST be 10 digits!"); } phones.forEach(len) 

I would replace the numbers with something like x , then check against predefined patterns: 我将用x代替数字,然后检查预定义的模式:

function check(num) {
  let pattern = '';
  for (let i = 0; i < num.length; i++) {
    pattern += num[i] >= '0' && num[i] <= '9' ? 'x' : num[i];
  }

  return ['xxx-xxx-xxxx', 'xxxxxxxxxx', '(xxx)xxxxxxx', '(xxx)xxx-xxxx']
    .indexOf(pattern) >= 0;
}

For extra credit, find the bug in the above program. 为了获得更多荣誉,请在上述程序中找到错误。

However, you don't really need to do any of this. 但是,您实际上不需要执行任何操作。 You should be able to use the pattern attribute on the input element. 您应该能够在input元素上使用pattern属性。 That will also provide a better user experience. 这还将提供更好的用户体验。 For instance, you can style the input element using the :invalid pseudo-class, by putting a red border around it for example, to give the user real-time feedback that their input is not valid. 例如,您可以使用:invalid伪类为输入元素设置样式,例如在其周围放置一个红色边框,以向用户实时反馈其输入无效。 Yes, that takes a regular expression--what was your reason for not wanting to use a regular expression again? 是的,这需要一个正则表达式-您为什么不想再次使用正则表达式呢?

You can make it manually be: 您可以手动将其设置为:

  • Checking string size if it is the expected or not 检查字符串大小是否符合预期
  • split the string to char array then parse them as integers inside a try block if numberFormatException is thrown it should be a bracket ( ) or - 将字符串拆分为char数组,然后在try块中将它们解析为整数(如果引发numberFormatException,则应为方括号()或-

Basic example of extracting the input data to Array 将输入数据提取到Array的基本示例

 function test() { var phnTest = document.getElementById('phone').value; var strArray = []; strArray = phnTest.split(''); document.getElementById('p').innerHTML = strArray; } 
  <form action="demo_form.asp"> Phone <input id="phone" type="text" name="phone"><br> <input type="button" value='Submit' onclick="test()"> </form> <p id='p'></p> 

This is dependent on how the data is structured, if you need to search a body of text and so on, but basics would be... 这取决于数据的结构方式,如果您需要搜索文本主体等,则基本知识将是...

If it's a simple pull from an <input> , grab the data... 如果是从<input>的简单提取,则获取数据...

Take the input data, and generate an array with each character. 获取输入数据,并为每个字符生成一个数组。 You could then test, say strArray[3] , for a dash or a dot. 然后可以测试,例如说strArray[3]是否为破折号或点。 If not present, it can continue along to check for seven numbers in a row and so on. 如果不存在,它可以继续检查连续七个数字,依此类推。

This is going to be extremely consuming and require a number of conditionals to be checked. 这将非常耗费资源,并且需要检查许多条件。 I assume the "without RegEx" is a requirement for a project or such, if not, recommend learning and using RegEx. 我认为“无RegEx”是项目的要求,如果不是这样,建议您学习和使用RegEx。

Hope this gets you going. 希望这能帮助您前进。

This is my attempt. 这是我的尝试。 The key is creating an array from the string then filtering out any non numerical characters. 关键是从字符串创建一个数组,然后过滤掉所有非数字字符。 It would be easier to use regular expression though. 但是使用正则表达式会更容易。 just 只是

number.replace(/(\D+)/g, '')

 const numbers = [ '123-456-7890', '1234567890', '(123)4567890', '(123)456-7890', '+61(123) 456-7890', '12345', '))))01/34$89.77(99' ] // validate a phone number function validate(number) { const digits = clean(number) console.log({ number, digits, length: digits.length, pass: digits.length === 10 }) } // remove any non digits from the number function clean(number) { return Array.from(number).filter(char => { return !isNaN(char) && char !== ' ' }).join('') } numbers.forEach(validate) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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