mikeerickson / validatorjs

A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
https://www.npmjs.com/package/validatorjs
MIT License
1.77k stars 280 forks source link

Local Server URL Marked as Invalid #445

Open GazEdge opened 2 years ago

GazEdge commented 2 years ago

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;
}
jershell commented 2 years ago

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 commented 2 years ago

So, to fix this I used

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

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