1

About validation URL format: regex using:

const regex = /^(?:(?:https?):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)(?:\.(?:[a-zA-Z0-9]-*)*[a-zA-Z0-9]+)*(?:\.(?:[a-zA-Z]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;

should pass:

const string1 = 'http://www.example.com'

const string2 = 'http://example.com'

const string3 = 'www.example.com'

const string4 = 'example.com'

should fail: const string5 = 'www.example' const string6 = 'http://www.example'

but string5 , string6 still pass, I just newbie regex.

Link reference: https://jsbin.com/hegocoyoge/edit?js,console

lifeisbeautiful
  • 817
  • 1
  • 8
  • 18

3 Answers3

0

Your regex seems very complex. It doesn't have to be.. Try this:

var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = 'www.google.com';
if (t.match(regex)) {
  console.log("This is a valid url");
} else {
  console.log("This is not a valid url");
}
Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46
0

Why don't you use this simple compact regex, instead of your so big unmaintainable regex? Which seems to satisfy your exact requirements mentioned in your post's samples.

^(http:\/\/)?(www\.)?\w+\.\w{1,3}$

Demo

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
-1

I'll highly recommend use some library. For example validator. Authors already solved these problems. If you still want to implement your own (unreadable) regEx try to look to source of some isEmail library like: https://github.com/chriso/validator.js/blob/master/src/lib/isEmail.js

Jakub Švehla
  • 21
  • 1
  • 3
  • Thanks for your suggestion, I'm using it in my project, but not enough for validate. So i need combine with regex for make sure validation is correct – Xuân Bình Dec 03 '18 at 07:39