Panagiotis Panagiotis - 1 year ago 108
Javascript Question

Javascript: Website url validation with regex

I'm working on create a regular expression in javascript to validate website urls. I searched a bit in the stackoverflow community and i did not find something to be completed helpful.

My regex until now: /(https?:\/\/)?(www\.)?[a-zA-Z0-9]+\.[a-zA-Z]{2,}/g

But it seems to fail and pass the validation for the url with two w like

Should pass the test of regex:

Should not pass the test of regex:

Any suggestions or thoughts?

Answer Source

Even if this answer is a bit too much for this Problem, it illustrates the problem: Even if it might be possible to create a regexp to check the url, it is much simpler and more robust to parse the URL and "create a real Object", on/with which the overall test can be decomposed to a number of smaller tests.

So probably the builtin URL constructor of modern browsers may help you here (LINK 1, LINK 2).

One approach to test you url might look like this:

function testURL (urlstring) {
    var errors = [];
    try {
        var url = new URL(urlstring);

        if (!/https/.test(url.protocol)) {
           errors.push('wrong protocol');

        //more tests here

    } catch(err) {
      //something went really wrong
      //log the error here

    } finally {
      return errors;

if (testURL('mr.bean').length == 0) { runSomething(); }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download