I need to validate the first four digits in a phone number which should be "5678" in nodeJs how should I do it. Which validator library should I use
Asked
Active
Viewed 808 times
0
-
2Stack Overflow expects you to [try to solve your own problem first](//stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into in [a minimal reproducible example](//stackoverflow.com/help/minimal-reproducible-example). For more information, please see [How to Ask](//stackoverflow.com/help/how-to-ask) and take the tour of the site. – Olaia Nov 08 '19 at 08:52
-
You don't need a library to do that, you can use a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). – TGrif Nov 08 '19 at 10:00
2 Answers
0
It is best practice to depends on external library only if you need it, in my opinion.
In your case, you can check if your phone number start with "5678" with a very simple regular expression:
const validate_phone = /^5678/
var phone_number = '5678122535'
console.log(validate_phone.test(phone_number)) // true
var phone_number = '1567812253'
console.log(validate_phone.test(phone_number)) // false
^
stand for matches beginning of input
test
stand for executes a search for a match between a regular expression and a specified string

TGrif
- 5,725
- 9
- 31
- 52
-
i did this: if(number.charAt(0)==5 && number.charAt(1)==6 && number.charAt(2)==7 && number.charAt(3)==8 ){ } else{ return res.json('Number Should start with 5678') } – Amaan Imtiyaz Nov 11 '19 at 19:09
-
-
I think you should now use this method even its correct since it lacks code readability. – aaditya Dec 02 '19 at 09:33
0
You could use substring function which is better then regular expression in terms of complexity.
const string = "56789012345" ;
string.substring(0,4)==="5678" ? true : false ;

aaditya
- 555
- 7
- 19