ruby - rails validation regular expression for www and http -


i want validate form input http:// , www not allowed. regex work?

for example:

allowed

google.com

not allowed

model

valid_domain_regex = ???

validates :domain, format: { with: valid_domain_regex }

since http:// contains many forward slashes, use ruby's %r{} regex literal syntax.

def has_forbidden_prefix?(string)   string =~ %r{^(http://|www)} end 

this return nil, falsy, if string not start http:// or www.

it return 0, truthy (the offset of first match) if string does.

you can use validate :some_method_name call custom validation method in model, structure follows

model mything   validate :no_forbidden_prefix    private    def has_forbidden_prefix?(string)     string =~ %r{^(http://|www)}   end    def no_forbidden_prefix     if has_forbidden_prefix?(uri)       errors.add :domain, 'the uri cannot start "http://" or "www"'     end   end end 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -