1

I need to validate the url using regex. The valid formats that should be accepted are as follows:

users.kathir.com www.kathir.com 

I am currently using the following regex:

^[a-z0-9-]+(\.[a-z0-9-])+(.[a-z]) 

But it accepts www.google as the valid one, but it should accept either google.com or www.google.com only. Please suggest

1
  • If you're only interested in capturing top-level domains that end in .com / .edu / etc., then you can literally place those characters to be validated in the last section. ....(com|edu) rather than the character class .[a-z]. You should update your question to be very specific about what you want to validate rather than four examples only showing one example of an invalid URL Commented May 11, 2012 at 12:00

2 Answers 2

2

I use this, works pretty well:

function checkUrl(url){ return url.match(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/); } 

Hope that helps :)

Sign up to request clarification or add additional context in comments.

Comments

1

The answer provided by user will also validate those regex in which there is no .com|edu|org etc at the end to make it more appropriate I have modify the regex which works fine for me and also want to share with you

var pattern = /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])+(.[a-z])?/; var regex = new RegExp(pattern); var website_url = $("#website_url").val();// url of the website if (website_url.match(regex)) { return true } else { return false; } 

if you like it do an Upvote

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.