Search code examples
javascriptreactjsregexip-address

RegEx IP Adress bug


in my react app I have a Input that validates if the string is an IPV4 Address or not.

This is my RegEx:

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Testcases:

192.168.0.1

  1. In my app: true
  2. On some random regex test website: true

192.168.0.

  1. In my app: false
  2. On some random regex test website: false

192.168.0

  1. In my app: true
  2. On some random regex test website: false

192.168.

  1. In my App: false
  2. On some random regex test website: false

192.168

  1. In my app: true
  2. On some random regex test website: false

i have no clue whats wrong here... on some random regex test website my regex string seems to work great but in my app it doesnt...

mb one of you knows anything related to this problem...

thanks for your time david


Solution

  • I used it like this in my code:

    const ipAddressValidationRegExString = '^(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])$'
    

    and the problem was the \\

    Correct regex:

    const ipAddressValidationRegExString = '^(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])**\\\\**.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])**\\\\**.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])**\\\\**.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])$'