0

I have an image url regular expression which is being used to validate a image on the form using ng-pattern directive.

Currently I'm struggling to accomodate for cases like https://google.com.png. Any help would be really appreciated.

Regex:

'^((?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?)\.(png|jpg|jpeg|gif|PNG|JPG|JPEG|GIF)$'

Better to view here:

https://regex101.com/r/dH1wT6/1

Cœur
  • 37,241
  • 25
  • 195
  • 267
Piyush Chauhan
  • 1,523
  • 2
  • 24
  • 37
  • Possible duplicate of [What is a good regular expression to match a URL?](http://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url) – nicael Jul 29 '16 at 05:21
  • You just use the regex to match the URL and then append to this regex whatever you need. – nicael Jul 29 '16 at 05:22

1 Answers1

1

Simplifying the regex :

^(?!mailto)(?:https?|ftp):\/(?:\/?(?:[.#@?=]?[a-z0-9\u00a1-\uffff]+)+)+[.]?(?:png|jpe?g|gif)$

Need to use the i flag for this to make the search not case sensitive.

But you should verify with your list of url's if this allows to much or to little.

Can test it here

If you put the regex in a javascript string, don't forget that you need to backslash the backslashes.

LukStorms
  • 28,916
  • 5
  • 31
  • 45