CSenshi

IPv6 validation

Jun 14th, 2020
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   ipv6: function (val, req, attribute) {
  2.     if (typeof val != 'string')
  3.       return false;
  4.  
  5.     // regex to check that each hextet is valid
  6.     var er = /^[0-9a-f]+$/;
  7.     // ipv6 hextets are delimited by colon
  8.     hextets = val.split(':');
  9.  
  10.     // check 1: ipv6 should contain only one consecutive colons
  11.     colons = val.match(/::/);
  12.     if (colons != null && val.match(/::/g).length > 1)
  13.       return false;
  14.  
  15.     // check 2: ipv6 should not be ending or starting with colon
  16.     //          edge case: not with consecutive colons
  17.     if (val[0] == ':' && (colons == null || (colons != null && colons.index != 0)))
  18.       return false;
  19.     if (val[val.length - 1] == ':' && (colons == null || (colons != null && colons.index != val.length - 2)))
  20.       return false;
  21.  
  22.     // check 3: ipv6 should contain no less than 3 sector
  23.     //         minimum ipv6 addres - ::1
  24.     if (3 > hextets.length)
  25.       return false;
  26.  
  27.     // check 4: ipv6 should contain no more than 8 sectors
  28.     //         only 1 edge case: when first or last sector is ommited
  29.     var isEdgeCase = (hextets.length == 9 && colons != null && (colons.index == 0 || colons.index == val.length - 2));
  30.     if (hextets.length > 8 && !isEdgeCase)
  31.       return false;
  32.  
  33.     // check 5: ipv6 should contain exactly one consecutive colons if it has less than 8 sectors
  34.     if (hextets.length != 8 && colons == null)
  35.       return false;
  36.  
  37.     for (let i = 0; i < hextets.length; i++) {
  38.       const element = hextets[i];
  39.  
  40.       if (element.length == 0)
  41.         continue;
  42.  
  43.       // check 6: all of hextets should contain numbers from 0 to f (in hexadecimal)
  44.       if (!er.test(element))
  45.         return false;
  46.  
  47.       // check 7: all of hextet values should be less then ffff (in hexadeimal)
  48.       //          checking using length of hextet. lowest invalid value's length is 5.
  49.       //          so all valid hextets are length of 4 or less
  50.       if (element.length > 4)
  51.         return false;
  52.     }
  53.     return true;
  54.   }
Add Comment
Please, Sign In to add comment