Regex to validate port number

Number() is the function you want "123a" returns NAN

parseInt() truncates trailing letters "123a" returns 123

<input type="text" id="txtFld" onblur="if(Number(this.value)>0 && Number(this.value)<65536){alert('valid port number');}" />
  • jsfiddle

When, we search "how to validate port number" on Google we unfortunately land here

However (except if you have really no other choice...),

Regex is clearly not the way to validate a port number !

"One" (slightly better) way may be:

step 1: Convert your string into number, and return FALSE if it fails
step 2: return TRUE if your number is in [1-65535] range, and FALSE otherwise

Various reasons, why Regex is not the right way ?

  • Code readability (would takes few minutes to understand)
  • Code robustness (there are various ways to introduce a typo, a unitary test would be required)
  • Code flexibility (what if port number can be extended to a 64-bits number !?)
  • etc. ...

What exactly do you mean by not working?

You could try something like so: ^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$ (obtained from here).

This will make sure that any given string is numeric and between the range of 0 and 65535.

Assuming your regular expression matches the same range, it is missing the start and end anchors (^ and $ respectively), so it would allow other strings besides the actual port.

Update 2 Feb 2022: Fixed the regex to reject values like 00 etc. The updated regex is sourced from the comment below. This regex can be better understood and visualized here: https://www.debuggex.com/r/jjEFZZQ34aPvCBMA