Ask A Question

Notifications

You’re not receiving notifications from this thread.

Any good regex rules for validation?

Tim Cheung asked in General

Currently, i am searching regex rules for validate url. And i am struggled how to build this from scratch. Is anyone have a good resources on this topic?

Reply

Just find out this site, when you type the regex rule, it will explain it instantly. It's really cool.

https://regex101.com/

Reply

Validating URLs is tough for the same reasons that validation on emails is tough. You can't verify the url or email is correct or live, only that it fits a format with regex.

It looks like Diego's regex here is the best option for correctness. https://mathiasbynens.be/demo/url-regex

Another great site for testing regex is http://rubular.com

Reply

Thank Chris, you save me ton of time :) I own you a starbuck!

Diego's regex look prefect for me, and i just realize the jquery validation plugins "formvalidation.io" also using this rule for validate url

Below is the ruby version i use

/\A(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-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,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i
Reply

Thanks to both for the information. I've been looking for some regex tips on validating URLs and some better email validation techniques. :)

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.