0

EDIT: I am not allowed to use regular expressions for this!

I have an assignment to validate 4 different types of phone numbers through string manipulation in javascript. I must be able to print out the final phone number into a "receipt" as this is for a pizza intake form in HTML.

I have all the code working minus this validation. These are the phone number types I need to validate: 1. ddd-ddd-dddd 2. dddddddddd 3. (ddd)ddddddd 4. (ddd)ddd-dddd

I also must provide an alert if the number is not in the required formats

kboyle140
  • 51
  • 1
  • 1
  • 4
  • Welcome to StackOverflow! Please edit your question and include your code, so we can point you in the right direction. We're more than happy to help, but without sharing your attempt(s), we won't just write the code for you from scratch :) [**This is a good starting point**](https://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number). – Tyler Roper Dec 06 '18 at 03:50
  • 1
    Have you tried regular expressions? – Praveen Dec 06 '18 at 03:58
  • what you have tried so far? – xkeshav Dec 06 '18 at 04:04

3 Answers3

0

Welcome to the overflow of stacks! While you don't have any code, I believe I may be able to help. The best way to accomplish this is to use a regular expression. an example:

var phoneRegex = /^(\+?( |-|\.)?\d{1,2}( |-|\.)?)?(\(?\d{3}\)?|\d{3})( |-|\.)?(\d{3}( |-|\.)?\d{4})$/gi;

function testPhoneNum(possibleNumber) {
  return phoneRegex.test(possibleNumber);
}

console.log(testPhoneNum('123-456-7890'))
console.log(testPhoneNum('heck no'))

of course that regular expression won't work for all phone numbers, you'll have to write your own, for your own use case. It is just meant as an example to get you started.

  • forgot to mention, and dont think this is worth an edit, but the regex i wrote will *most likely* work with all of those formats, but it will also work with more, so you definitely *will* have to modify it to get the output you desire. (I originally wrote it for a lib i'm building, so it had to have a wide application spectrum) – Liz Ainslie Dec 06 '18 at 04:21
  • Thank you! unfortunately cannot use regular expressions in this solution! – kboyle140 Dec 06 '18 at 04:57
0

You can try this mate.

^\(?\d{3}\)?\-?\d{3}\-?\d{4}$

Demo

Explanation

  • ^ - Anchor to start of string.
  • \(?\d{3}\)?\-? This will match (3 digit number), (3 digit number)- , 3 digit number.
  • \d{3}\-? - This will match 3 digit number, 3 digit number followed by -.
  • \d{4} - This will match any 4 digit number.
  • $ - Anchor to end of the string.

Example

const regex = /^\(?\d{3}\)?\-?\d{3}\-?\d{4}$/gm;
const str = `999-999-9999
(123)123-1454
1234567890
(123)1231234
a122-123-1234
(123)-123-12345
(123)-(123)-(1234)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

This is just a demo code but when you have only 4 types of format than can do this.

  1. first remove (, ) and - and check whether the string has only numbers?
  2. then again check the index of dash and parenthesis in the original string

let p1 = '123-456-7887';
let p2 = '1233333333';
let p3 = '(123)7878777';
let p4 = '(123)456-7887';
let p5 = '(123456-7887';
let p6 = '(123-456-7887';



const validatePhone = (str) => {
  const withoutDash = str.replace(/[\s()-]+/gi, "");
  const firstP = str.indexOf('(');
  const lastP = str.lastIndexOf(')');
  const firstD = str.indexOf('-');
  const lastD = str.lastIndexOf('-');
  
  console.log(withoutDash);
  const onlyNumber = /^\d+$/.test(withoutDash);
  let valid = false;
  if (onlyNumber) {
  if (firstP === 0 && lastP === 4) {
      valid = true;
    if(firstD === 8 && lastD === 8 ) {
      valid = true;
    }
  } else if( firstD === 3 && lastD === 7) {
    valid = true;
  } 
  } else {
    valid = false;
  }
  return valid;
};

const isValid = validatePhone(p1);
console.log({isValid});
xkeshav
  • 53,360
  • 44
  • 177
  • 245