18

I am trying to validate strings in ruby. Any string which contains spaces,under scores or any special char should fail validation. The valid string should contain only chars a-zA-Z0-9 My code looks like.

def validate(string)
    regex ="/[^a-zA-Z0-9]$/
    if(string =~ regex)
        return "true"
    else
        return "false"
end

I am getting error: TypeError: type mismatch: String given.

Can anyone please let me know what is the correct way of doing this?

Mandar Dalvi
  • 179
  • 1
  • 1
  • 5

8 Answers8

14

If you are validating a line:

def validate(string)
  !string.match(/\A[a-zA-Z0-9]*\z/).nil?
end

No need for return on each.

Michael Papile
  • 6,836
  • 30
  • 30
5

You can just check if a special character is present in the string.

def validate str
 chars = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
 str.chars.detect {|ch| !chars.include?(ch)}.nil?
end

Result:

irb(main):005:0> validate "hello"
=> true
irb(main):006:0> validate "_90 "
=> false
rohit89
  • 5,745
  • 2
  • 25
  • 42
  • 4
    I suggest `str.chars.all? {|ch| chars.include?(ch)}` (for better readability). Also, using `chars` as a variable name along with the method `chars` could be confusing. Best to avoid variable names that are the names of methods. – Cary Swoveland Oct 21 '15 at 20:18
5
def alpha_numeric?(char)  
 
   if (char =~ /[[:alpha:]]/ || char =~ /[[:digit:]]/)
      true
   else
      false
   end

end

OR

def alpha_numeric?(char)  
 
   if (char =~ /[[:alnum:]]/)
      true
   else
      false
   end

end

We are using regular expressions that match letters & digits:

The above [[:alpha:]] ,[[:digit:]] and [[:alnum:]] are POSIX bracket expressions, and they have the advantage of matching Unicode characters in their category. Hope this helps.

checkout the link below for more options: Ruby: How to find out if a character is a letter or a digit?

DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
Enow B. Mbi
  • 309
  • 3
  • 8
1

No regex:

def validate(str)
  str.count("^a-zA-Z0-9").zero?  # ^ means "not"
end
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • It's curious that all but one of the answers has received a downvote. I received mine today. – Cary Swoveland Sep 28 '20 at 22:11
  • kind of odd to say no regex since you're passing in a regex – drewish Jun 23 '21 at 16:34
  • @drewish Sure, it's similar. A valid regex would be `/[^a-zA-Z0-9]/` (as in the answer by Joshua Pinter. – steenslag Jun 23 '21 at 22:37
  • No, I was mistaken. I thought the count method was just converting the string version of a regex you passed in to a a regex. Looking at [the docs](https://ruby-doc.org/core-2.6/String.html#method-i-count) I'm understanding your point that they use the same character class syntax, but that it's not a full regex. – drewish Aug 06 '21 at 19:07
1

Great answers above but just FYI, your error message is because you started your regex with a double quote ". You'll notice you have an odd number (5) of double quotes in your method.

Additionally, it's likely you want to return true and false as values rather than as quoted strings.

Aaron Washburn
  • 300
  • 2
  • 10
1

Similar to the very efficient regex-ish approach mentioned already by @steenslag and nearly just as fast:

str.tr("a-zA-Z0-9", "").length.zero?

OR

str.tr("a-zA-Z0-9", "") == 0

One benefit of using tr though is that you could also optionally analyze the results using the same basic formula:

str = "ABCxyz*123$"

rejected_chars = str.tr("a-zA-Z0-9", "")
#=>  *$

is_valid = rejected_chars.length.zero?
#=> false
0

Similar to @rohit89:

VALID_CHARS = [*?a..?z, *?A..?Z, *'0'..'9']
  #=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
  #    "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
  #    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
  #    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
  #    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

def all_valid_chars?(str)
  a = str.chars
  a == a & VALID_CHARS
end

all_valid_chars?('a9Z3')  #=> true
all_valid_chars?('a9 Z3') #=> false
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Use .match? in Ruby 2.4+.

Ruby 2.4 introduced a convenient boolean-returning .match? method.

In your case, I would do something like this:

# Checks for any characters other than letters and numbers.
# Returns true if there are none. Returns false if there are one or more.
#
def valid?( string )
  !string.match?( /[^a-zA-Z0-9]/ ) # NOTE: ^ inside [] set turns it into a negated set.
end
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245