S
S
sophiko2014-08-27 15:50:58
Regular Expressions
sophiko, 2014-08-27 15:50:58

Regular expressions, what's wrong with $?

Hello,
I rarely use expressions.
I wrote a code to check the entered phone number (according to the task, 2 format options:
a) +7 123 12312345;
b) 123 12312345;)
Code:

function checkPhone(input){
  var patt = /^\+7\s\d{3}\s\d{7}|^\d{3}\s\d{7}/;

  var res = patt.test(input);
  return res;
};
//А это тест для проверки и что должно выдавать:
checkPhone('+7 123 12312345');//true
checkPhone('123 12312345'); // true
checkPhone('123 12312345aaa'); // false

In the latter, it returns erroneously true.
I found the $ end of line operator, but when I write:
/^\+7\s\d{3}\s\d{7}$|^\d{3}\s\d{7}$/
my browser tells me all three tests are false.
Tell me, please, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kompi, 2014-08-27
@sophiko

12312345 - only 8 digits, and you have d{7} in the regular expression, corresponding to d{7}$ - all will be false;
Shorter option:/^(\+7\s)?\d{3}\s\d{8}$/

E
Evgeny Petrov, 2014-08-27
@Petroveg

It is obvious that there cannot be 8 digits in a Russian telephone number... And do not forget that a person can enter a space where it is not necessary.

function checkPhone(input){
  var result = /^\s*(?:\+7\s*)?(?:\d\s*?){10}$/.test(input);

  console.log(result);
  return result;
};

//А это тест для проверки и что должно выдавать:
checkPhone('+7 123 1234567'); // true
checkPhone('123 1234567'); // true
checkPhone('123 1234567aaa'); // false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question