| Viewed 181 times

How to check IPv4 Validation in Javascript?


I need a function that takes a string (IPv4 address in standard dot-decimal format) and returns true if the IP is valid or false if it's not. For information on IPv4 formatting, please refer to the resources in the

1 Answer
Mohammad Qandeel
Answered
10

you can use this method wich will return

TRUE if IPv4 address in standard dot-decimal format. 

FALSE if IPv4 address not-in standard dot-decimal format. 

function isValidIP(str) {
  if(/\s/g.test(str) === true) {
    return false;
  } else if(str.split('.').filter(x => x === Number(x).toString()).length !== 4) {
    return false;
  } else {
    return str.split('.').every(x => Number(x) <= 255 && Number(x) >= 0);
  }
}

Example 

isValidIP('127.0.0.1') //true

 


Related Questions