DEV Community

loading...
Cover image for 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?

MELVIN GEORGE
Hi, I'm Melvin George, A web developer, and a blogger.
Originally published at melvingeorge.me ใƒป2 min read

Originally posted here!

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 number
const 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 number
const num = 8080;

regexExp.test(num); // true
Enter fullscreen mode Exit fullscreen mode

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 number
const 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;
Enter fullscreen mode Exit fullscreen mode

Now let's write a number which is a valid port number like this,

// Regular expression to check if number is a valid port number
const 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 number
const num = 8080;
Enter fullscreen mode Exit fullscreen mode

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 number
const 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 number
const num = 8080;

regexExp.test(str); // true
Enter fullscreen mode Exit fullscreen mode
  • 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.

See the above example live in JSBin.

If you want this as a utility function which you can reuse, here it is,

/* Check if number is a valid port number */
function checkIfValidPortnumber(num) {
  // Regular expression to check if number is a valid port number
  const 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 function
checkIfValidPortnumber(8080); // true
checkIfValidPortnumber(65536); // false
Enter fullscreen mode Exit fullscreen mode

That's all! ๐Ÿ˜ƒ

Feel free to share if you found this useful ๐Ÿ˜ƒ.


Discussion (0)