20

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");
    }
});
Toto
  • 89,455
  • 62
  • 89
  • 125
public9nf
  • 1,311
  • 3
  • 18
  • 48

5 Answers5

35

Remove the |www\.?

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
Ant P
  • 24,820
  • 5
  • 68
  • 105
3

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')
DGS
  • 6,015
  • 1
  • 21
  • 37
1

Shorter way:

(\w*\W*)?\w*(\.(\w)+)+(\W\d+)?(\/\w*(\W*\w)*)*

You can test it in this wonderful regex editor: https://regex101.com/

Raphael
  • 69
  • 1
  • 2
  • 9
0

This will work:

(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*

Hope it may help you

EdsonF
  • 2,719
  • 3
  • 30
  • 34
0
^http(s?):\/\/(www\.)?(((\w+(([\.\-]{1}([a-z]{2,})+)+)(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*$)|(\w+((\.([a-z]{2,})+)+)(\:[0-9]{1,5}(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*$)))|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(([0-9]|([1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]+)+)(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*)((\:[0-9]{1,5}(\/[a-zA-Z0-9\_\=\?\&\.\#\-\W]*)*$)*))$
In this http is mandatory and it can take port and sub resources also.
e.g http://example.com
    https://example.qwerty.com/id
    https://example.com:8989
    http://example.qwerty.com:8989/id
    https://10.1.1.1/id
    https://10.1.1.1:9090/id