let EX1=/^(1\s?)?\d\d\d-\d\d\d-\d\d\d\d$/;
let EX2=/^(1\s?)?\(\d\d\d\)\s?\d\d\d-\d\d\d\d$/;
let EX3=/^(1\s?)?\d\d\d\s?\d\d\d\s?\d\d\d\d$/;
let EX4=/^(1\s?)?\d\d\d\d\d\d\d\d\d\d$/;
function telephoneCheck(str) {
let result=false;
EX1.test(str)?result=true:EX2.test(str)?result=true:EX3.test(str)?result=true:EX4.test(str)?result=true:result=false;
return result;
}
console.log(telephoneCheck("1 555-555-5555"));
I could not get the regex to work and not being confident in my regex skills I gave up and used code. I was thinking along the right lines but forgot about the ^ $
function telephoneCheck(str) {
// fail early
if (noAlpha(str)) {
if (dataValidLen(str) !== 0) {
if (dataValidLen(str) === 11) {
// check formatting
if (str[1] === " "){
if (str[5] === " " && str[9] === " "){
return true;
}
if (str[5] === "-" && str[9] === "-"){
return true;
}
if (str[2] === "(" && str[6] === ")" && str[7] === " " && str[11] === "-") {
return true;
}
}
if (str[1] === "("){
if (str[5] === ")" && str[9] === "-"){
return true;
}
}
}
if (dataValidLen(str) === 10) {
if (str.length === 10){
// no formatting
return true;
}
// check formatting
if (str[3] === "-" && str[7] === "-"){
return true;
}
if (str[3] === " " && str[7] === " "){
return true;
}
if (str[0] === "("){
if (str[4] === ")" && str[8] === "-"){
return true;
}
}
}
console.log("Invalid format!");
return false
}
console.log("Invalid number of digits!");
return false;
}
console.log("Alpha chacters not allowed!");
return false;
}
function noAlpha(str) {
let alphaTest = /[A-z]/; // test for alpha
if (!alphaTest.test(str)){ // if no alpha continue
return true;
}
return false;
}
function dataValidLen(str) {
let formatTest = /(\W*)(\d)(\s*)/g; // group symbols and numeric
let result = str.replace(formatTest, '$2' ); // extract numbers
// data valid 11?
if (result.length === 11 && result[0] === "1") {
return 11;
}
// data valid 10?
if (result.length === 10) {
return 10;
}
// data invalid
return 0;
}
console.log(telephoneCheck("(223)456-7890"));
That feels like a philosophical question! Sure, there must be lots of different ways to do the project, though I don’t think I will attempt it again for a long time.
What about form validations where you want to check that the user’s input conforms to a standard before you submit the data to the server? I think I’m going to save this in my toolbox.
function telephoneCheck(str) {
// Case that there is no parenthesis
if((/^1?\s?\d{3}-?\s?\d{3}-?\s?\d{4}$/.test(str))) {
return true;
}
// Case that there is parenthesis
else if ((/^1?\s?\(\d{3}\)-?\s?\d{3}-?\s?\d{4}$/.test(str))) {
return true;
}
else {
return false;
}
}
The parentheses are for a group, the bracket will find any of the characters inside.
You can test this here (on w3schools.com): Tryit Editor v3.7
If you change the sample sentence to “Is this all red there is?”
The regex /[red]/g will match any of these letters and give you r,e,d,e,r,e
The regex /(red)/g will only match exactly that group and give you red as result.
Ahhhh, I get it now, thank you very much for the explanation!
I was confused because we had used [-|\s] in class, but I get now that, since it was just 1 char there, it was ok to use the brackets.
Thanks again!
I played with this a bit as I was not happy with my original solution. Thought I will share it maybe somebody finds it useful
//
// Revised attempt based on Ramón Huidobro's solution
//
// I could simply do this:
// const regex = /^(1\s?)?\(\d{3}\)\s?\d{3}-\d{4}$|^(1\s?)?\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/;
// return (regex.test(str))
// But then I can't give guidance to the user
function telephoneCheck(str) {
const regex = /^(1\s?)?\(\d{3}\)\s?\d{3}-\d{4}$|^(1\s?)?\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/;
// no alpha allowed
if (!(/[A-z]/.test(str))){
// get data
const data = getData(str)
// if len = 11 is country code = 1
if (data.length === 11){
if (data[0] !== "1"){
//console.log("Invalid country code, must be 1");
//return false;
return("Invalid country code, must be 1");
}
}
// data length
if ((data.length === 11 && data[0] === "1") | data.length === 10){
// check format
if (regex.test(str)){
//console.log("Ok!");
//return true;
return("Ok");
}
//console.log("Invalid format!");
// return false
return ("Invalid format!");
}
//console.log("Invalid number of digits!");
//return false;
return("Invalid number of digits!")
}
//console.log("Alpha chacters not allowed!");
//return false;
return ("Alpha chacters not allowed!");
}
function getData(str) {
let formatTest = /(\W*)(\d)(\s*)/g; // group symbols, numeric and space
let result = str.replace(formatTest, '$2' ); // extract numbers
return result;
}
testNumbers = [
// number, expected result
["1263457890", "Ok"],
["(263) 145-7890", "Ok"],
["263-145-7890", "Ok"],
["1(263)45-7890", "Invalid format!"],
["1(263)45-789", "Invalid number of digits!"],
["1(263)451-7890", "Ok"],
["2(263)451-7890", "Invalid country code, must be 1"]
]
let testResult = "";
let testStatus = [];
for (let i = 0; i < testNumbers.length; i++){
//console.log(telephoneCheck(testNumbers[i][0]));
testResult = (telephoneCheck(testNumbers[i][0]));
if (testResult === testNumbers[i][1]){
testStatus.push(`test ${i} ok`);
}
else {
testStatus.push(`test ${i} fail`);
}
}
console.log("Test Results: ", testStatus);
Yes, it can be done. And it is good technical solution. But what about the user? If you return false to the user the user will say ok, but what is incorrect? You could use it on the server side to check the input received via an API. The API does not want to get into a dialogue with the user.
On the frontend side you would want to give more useful feedback to the user. The API documentation would specify the expected format, so you want to ensure the user’s input conforms and when it does not you want to give specific guidance to the user. That is why I started playing with testing for specific conditions so that specific messages can be presented.
What’s interesting about this is that frontend validation could end up being more involved than backend validation. The use case impacts the code.
Oh, definitely. If the scope of this project were actual interaction with a user I’d approach it differently since just giving a false result isn’t particularly meaningful to them. I appreciate the effort you put into your expanded solution as it resembles what I’d like to see as an end user.
I wound up going to Felienne’s (this week’s guest) Twitter account and she touched on meaningful error messages and that’s been on my mind since.