Nodejs IP Address Format Check ipv4Address()

Here you can find the source of ipv4Address()

Method Source Code

// Implement String#ipv4_address?, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots.
////from   w w w .  ja  v a  2s . c o  m
// It should only accept addresses in canonical representation, so no leading 0s, spaces etc.


//
// Test.describe("Basic tests",_=>{
// Test.assertEquals("".ipv4Address(), false);
// Test.assertEquals("127.0.0.1".ipv4Address(), true);
// Test.assertEquals("0.0.0.0".ipv4Address(), true);
// Test.assertEquals("255.255.255.255".ipv4Address(), true);
// Test.assertEquals("10.20.30.40".ipv4Address(), true);
// Test.assertEquals("10.256.30.40".ipv4Address(), false);
// Test.assertEquals("10.20.030.40".ipv4Address(), false);
// Test.assertEquals("127.0.1".ipv4Address(), false);
// Test.assertEquals("127.0.0.0.1".ipv4Address(), false);
// Test.assertEquals("..255.255".ipv4Address(), false);
// Test.assertEquals("127.0.0.1\n".ipv4Address(), false);
// Test.assertEquals("\n127.0.0.1".ipv4Address(), false);
// Test.assertEquals(" 127.0.0.1".ipv4Address(), false);
// Test.assertEquals("127.0.0.1 ".ipv4Address(), false);
// Test.assertEquals(" 127.0.0.1 ".ipv4Address(), false);
// })

String.prototype.ipv4Address=function(){
  var newArr = this.split('.');
  if(newArr.length !== 4){
    return false;
  }
  var test1 = this.split('.').join('');
  var regexp = new RegExp("\\D+", "g");
  if(regexp.test(test1) === true){
    return false;
  }
  for(var i = 0; i < newArr.length; i++){
    if(newArr[i].length === 0){
      return false;
    }
    if(newArr[i].charAt(0) === "0" && newArr[i].length > 1){
  return false
}
  if(newArr[i] > 255 || newArr[i]<0){
    return false;
  }
  }
 return true;
 }

Related

  1. ipv4Address()
    String.prototype.ipv4Address = function() {
      return /^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|$)){4}$/.test(this);
    };
    
  2. ipv4Address()
    String.prototype.ipv4Address = function() {
      return /^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])(\.(?!$)|$)){4}$/.test(this);
    };
    
  3. ipv4Address()
    String.prototype.ipv4Address = function() {
      var ipv4 = this;
      if(ipv4.trim().length!=ipv4.length) return false;
      var arr = ipv4.split('.');
      if(arr.length!=4) return false;
      for(var i=0; i<arr.length; i++){
        if(!(checkWhiteSpace(arr[i]) && checkLeadZero(arr[i]) && checkForNum(arr[i]))){
          return false;
      return true;
    };
    function checkWhiteSpace(str){
      return str.trim().length == str.length;
    function checkLeadZero(str){
      if(str.length==1) return true;
      if(str.charAt(0)==0) return false;
      if(str.charAt(0)=='+') return false;
      else return true;
    function checkForNum(str){
      var num = parseInt(str);
      if(num>=0 && num<=255) {
        return true;
      }else {
        return false;