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
- www.google.com
- http://google.com
- http://www.google.com
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
Post a Comment