5

I had the following url validation regex:

/(ftp|https?)://[^ "]+$/

This is from the ref: Regular expression for URL validation (in JavaScript)

This works fine including cases like http://localhost:8080, but it also validates the below ones that i dont want. The above regex should not pass the below urls

 1. http://www.example..com
 2. http://.com
 3. http://.
 4. http://www.example. 

Kindly help as am a noob in regex

Second question, though not related to the question but regex is, when i validate null and undefined against the regex /^[a-z]+$/i i get true. Is this the default behavior or am i missing something over here?

15
  • what do you mean by fail? are they marked as valid or invalid? Commented Aug 21, 2013 at 17:57
  • check this - stackoverflow.com/a/8234912/1823389 Commented Aug 21, 2013 at 17:59
  • 2
    This has been so beat to death. Please, PLEASE, search before asking questions. Commented Aug 21, 2013 at 18:00
  • possible duplicate of regular expression for url Commented Aug 21, 2013 at 18:00
  • possible duplicate of url validation regex Commented Aug 21, 2013 at 18:00

3 Answers 3

8

Try this

function is_valid_url(url)
{
     return url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}

Call the is_valid_url(YOUR_WEBSITE_URL) function everywhere which you want to website validate.

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

3 Comments

Ok i am checking it now
{2,4} does not cover a large number of TLDs especially all the new ones that just came out. See data.iana.org/TLD/tlds-alpha-by-domain.txt using {2,22} would cover most.
it does validates \ and ˆ !
2

Try This ..

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});
</script>

Comments

0

I built this regex IP and DNS validation for javascript.

/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?((([a-z0-9])*[:]){1}|(([a-z0-9])*[.]){1}|(([0-9]){1,3}([.]|[:])){3}(([0-9]){1,3}[:]){1})([a-z]{2,5}|[0-9]{1,5})([.]([a-z0-9]){1,3})?(\/.*)?$/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.