Skip to content

Instantly share code, notes, and snippets.

@efarioli
Created December 5, 2016 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save efarioli/ffd869598e045fdc5c02e80fb1b5d417 to your computer and use it in GitHub Desktop.
Save efarioli/ffd869598e045fdc5c02e80fb1b5d417 to your computer and use it in GitHub Desktop.
Return true if the passed string is a valid US phone number. The user may fill out the form field any way they choose as long as it is a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants): 555-555-5555 ||| (555)555-5555 ||| (555) 555-5555 ||| 555 555 5555 ||| 5555555555 ||| 1…
//javascript
function telephoneCheck(str) {
if (!balancedParens(str)){
return false;
}
//remove whitespace
var newStr = str.replace(/\s/g, '');
//validation regular expression or pattern
var patt = /^1?\(?\d{3}-?\)?\d{3}-?\d{4}$/;
return patt.test(newStr);
}
telephoneCheck("555-555-5555");
function balancedParens(string){
var stack = [];
var pairs = {
'[':']',
'{':'}',
'(':')'
};
var closers = {
')': 1,
']': 1,
'}': 1
};
for(var i = 0; i < string.length; i++){
var cur = string[i];
if(pairs[cur]){
console.log(cur,"----",pairs[cur]);
stack.push(pairs[cur]);
} else if(cur in closers){
if(stack[stack.length -1] === cur){
stack.pop();
} else{
return false;
}
}
}
return !stack.length;
}
@Steven-zion
Copy link

this is top shit mate, great job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment