validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

Local Server URL Marked as Invalid

Open GazEdge opened this issue 3 years ago • 2 comments

v3.22.1

Local server URLs are not seen as valid.

Example here: https://codesandbox.io/s/npm-playground-forked-ne791

Code example here:

const Validator = require("validatorjs");

const validation = new Validator(
  {
    url1: "http://google.com", // valid
    url2: "http://localhost", // invalid
    url3: "http://localhost:8000", // invalid
    url4: "https://192.168.1.168", // invalid
    url5: "https://192.168.1.168:8000" // invalid
  },
  {
    url1: "url",
    url2: "url",
    url3: "url",
    url4: "url",
    url5: "url"
  }
);

if (validation.fails()) {
  let htmlStr = "";
  Object.values(validation.errors.all()).forEach((element) => {
    htmlStr = htmlStr + `<p>${element}</p>`;
  });

  document.getElementById("app").innerHTML = htmlStr;
}

GazEdge avatar Dec 09 '21 10:12 GazEdge

Also http://192.168.1.87:8080/debug marked as an invalid URL Any ipv6 address will invalid like this

http://[::1]:3000/projects/5fd65de50df52c1a6781df40/hooks

I think we can replace it

  url: function (url) {
    return /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_\+.~#?&/=]*)/i.test(url);
  },

on simular this

const isValid = (str) => {try { new URL(str); return true; } catch(e) { return false }};
  url: function (url) {
    return isValidt(url);
  },

it will work on node & browsers.

jershell avatar Jan 09 '22 14:01 jershell

So, to fix this I used

 validator.register('url', isValidUrl, undefined);

The third argument is undefined for using the default error messages.

jershell avatar Jan 09 '22 14:01 jershell