This website collects cookies to deliver better user experience
How to check if a number or a string is a valid port number in JavaScript?
How to check if a number or a string is a valid port number in JavaScript?
To check if a number or a string is a valid port number, we can use a regex expression to match for all the numbers from 0 till 65535 in JavaScript.
TL;DR
// Regular expression to check if number is a valid port numberconst regexExp =/^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$/gi;// a numberconst num =8080;regexExp.test(num);// true
This is the regex expression for matching almost all the test cases for a valid port number from 0 till 65535 in JavaScript.
// Regular expression to check if number is a valid port numberconst regexExp =/^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$/gi;
Now let's write a number which is a valid port number like this,
// Regular expression to check if number is a valid port numberconst regexExp =/^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$/gi;// a numberconst num =8080;
Now to test the number, we can use the test() method available in the regular expression we defined. It can be done like this,
// Regular expression to check if number is a valid port numberconst regexExp =/^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$/gi;// a numberconst num =8080;regexExp.test(str);// true
The test() method will accept a number type as an argument to test for a match.
The method will return boolean true if there is a match using the regular expression and false if not.
If you want this as a utility function which you can reuse, here it is,
/* Check if number is a valid port number */functioncheckIfValidPortnumber(num){// Regular expression to check if number is a valid port numberconst regexExp =/^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$/gi;return regexExp.test(num);}// Use the functioncheckIfValidPortnumber(8080);// truecheckIfValidPortnumber(65536);// false