Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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}$/
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 questionAsk a Question
731 491 924 answers to any question