Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Validation REGEX - URL just valid with http://

How it works

I have an input field to enter the URL of a Website and i wanna check it and if the URL is OK i will give the inputfield a class("validated_ok") and remove a class ("cf_required") and if its wrong the other way around.

Problem

The url should just be right if it is written with http:// but actually its also right with just www (www.google.ch). How i have to change the regex?

Javascript

// CHECK WEBSITE
$(".cf_required[name='website']").focusout(function() {
    var myVariable = $(this).val();
    if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
        $(this).addClass("validated_ok").removeClass("cf_required")
    } else {
        $(this).removeClass("validated_ok").addClass("cf_required");
    }
});
like image 534
public9nf Avatar asked Sep 02 '13 07:09

public9nf


2 Answers

Remove the |www\.?

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
like image 196
Ant P Avatar answered Oct 16 '22 08:10

Ant P


just change your regex to make http(s) required

/^http(s)?:\/\/(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test('www.google.com')
like image 40
DGS Avatar answered Oct 16 '22 08:10

DGS