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
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;
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;
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
- The
test()
method will accept anumber
type as an argument to test for a match. - The method will return boolean
true
if there is a match using the regular expression andfalse
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
That's all! 😃