The Ruby Way to do URL Validation
- Categories:
- ruby
As we know, to do URL validation we can use regular expression such as:
After I read blog post from Michael Bleigh, I realized that there is a Ruby way to do URL validation. The secret regexp
method of URI
module. It will regenerate a regular expression based on the protocol name parameter that you pass in. URI::regexp
will return 0 if URL is valid and return nil if URL is not valid.
If you use Rails, URI::regexp
can be plugged directly into your model validation.
Update
This approach seems flawed. When pass "http://" =~ URI::regexp("http")
it will returns 0 indicating the URL to be valid. So, I recommend to use the regular expression provided at the beginning of the post.
Thanks to Losk, who points out in the comments below.
- Tags:
- #rails
- #ruby
- #active record
- #tips
Sponsored Links
- Register to Digital Ocean cloud with this link and get $200 credit
- Looking for cheap CDN? Bunny is the answer
- Alternative Cloud besides AWS and Digital Ocean