Evlikosh Dawark
Evlikosh Dawark

Reputation: 640

Regular Expressions How to exclude entering other URL's than domain URL

Hello i wrote a regular expression to validate URL

jQuery.validator.addMethod("url_validation", function (value, element) {
    return this.optional(element) || /^([ \t+])?(([http|https|HTTPS|HTTP]+:\/\/))?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/i.test(value);
}, "error")

I could not find a way to prevent entering anything after entering the domain : for example : - "http://www.mydomain.uk/whateverthing.ext" i want to stop entering the "whateverthing after entering the domain . I could not figure out a way to solve this issue . can anyone give me a help?"(this will include validating the URL as well)

Upvotes: 1

Views: 182

Answers (1)

fge
fge

Reputation: 121810

OK, so you want two things:

  • validate the hostname;
  • validate that the part after the /, if / there is, is empty.

You can proceed as such:

  • validate your input against ^https?://([a-z0-9-]+(?:\.[a-z0-9-]+)*)/?(.*);
  • if the above does not match, you have an invalid URL;
  • grab group 2: if non empty, it means a non empty path, invalid URL;
  • grab group 1 and split it against \..
  • verify whether all groups are of length <= 255 and match ^[a-z0-9]+(-[a-z0-9]+)*$: if one doesn't, invalid URL.

And that doesn't take IP addresses in the hostname part...

I am surprised anyhow that jQuery doesn't have methods to check for that. Have you looked?

Edit: it has: http://docs.jquery.com/Plugins/Validation/Methods/url

Upvotes: 6

Related Questions