Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back end validation rails

How can I validate text column that it doesn't contain websites, examples can be :

www.google.com
google.com
http://gooogle.com
http://www.google.com
https://www.google.com
https://google.com

I want to do this on the front side but on the back end as well. I'm more interested in back end at the moment, as I will deal with the front end later

Question update:

Based on example provided by MrYoshiji, I've come up with case that is not covered:

http://rubular.com/r/VGgWyfIt7R

See the http://www.google.com in the middle of the text? and it is not matched? That is exactly what I need it to be matched. So I can throw validation error saying you can't put websites.

like image 377
Gandalf StormCrow Avatar asked Apr 01 '26 21:04

Gandalf StormCrow


1 Answers

I found a strong regexp, credits goes to @PhillPafford (PHP RegEx for "Website Name" If you upvote my answer, please upvote his first!):

/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/

To see it in action:

http://rubular.com/r/GOHHrucCdX


UPDATE:

This one will find the names anywhere in the text:

/(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/

Note that I removed the ^ at the start and the $ at the end to make it work within a text:

Rubular source:

^ Start of line

$ End of line

http://rubular.com/r/iEVzfv2U3O


@GandalfStormCrow noticed that the following is matched:

Since I was little.My first dog
                #^^^

The only way I see to solve this issue would be to replace little.My with little. My:

text.gsub(/\w\.[A-Z]/) { |matched_string| matched_string.gsub('.', '. ') }

See it in action:

1.9.3p489 :018 > text = "hello my name is robert.My dog"
 => "hello my name is robert.My dog" 
1.9.3p489 :019 > text.gsub(/\w\.[A-Z]/) { |matched_string| matched_string.gsub('.', '. ') }
 => "hello my name is robert. My dog" 
like image 181
MrYoshiji Avatar answered Apr 04 '26 09:04

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!