Nodejs IP Address Format Check ipv4Address()

Here you can find the source of ipv4Address()

Method Source Code

/*//from w  w w  .  j a  va2 s. c  o m
Implement String#ipv4_address?, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots.

It should only accept addresses in canonical representation, so no leading 0s, spaces etc.
*/

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;
   }
}

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 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;
    ...