Jeff
Jeff

Reputation: 4433

Ruby - Check if string only contains specific charaters and invalidate model

Is there a way to check if a string contains only illegal characters? These characters are not illegal if anything else is there, but if they are by themselves, they are illegal.

For example:

illegal_characters = ['$', '^', '\\']

so

'$'               # bad
'^^$^$^^\\\\^\\$' # bad
'$oh hey there'   # good

Is there a way to check for that?

Upvotes: 1

Views: 854

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

You could do this:

BADDIES = '$^\\'

def all_good?(str)
  str.delete(BADDIES).size > 0
end

all_good? '$'               # false
all_good? '^^$^$^^\\\\^\\$' # false
all_good? '$oh hey there'   # true
all_good? 'oh hey there'    # true

Upvotes: 0

engineersmnky
engineersmnky

Reputation: 29598

It is not elegant and maybe someone can offer a better answer but this will work.

illegal_strings = ['$', '^', '\\']
valid_string = Proc.new{ |s| !s.chars.all?{ |a| illegal_strings.include?(a) } }
# OR
# valid_string = Proc.new{ |s| !s.gsub(/[$^\\]/,'').empty?}
valid_string.call('$')
#=> false
valid_string.call('^^$^$^^\\\\^\\$')
#=> false
valid_string.call('$oh hey there')
#=> true

If this is Rails then Philip's answer is more appropriate

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19899

You didn't tag this rails, but you did say invalidate the model... so...

validates_format_of :myfield, without: /\A[$^\\]+\z/

Note that it's without, not with. So you're saying if myfield only contains those characters then fail.

If it's not rails, that regex will still do what you want.

Upvotes: 5

Related Questions