views:

468

answers:

3

Hi,

I want to use validates_format_of to validate a comma separated string with only letters (small and caps), and numbers.

So.

example1, example2, 22example44, ex24

not: ^&*, <> , asfasfsdafas<#%$#

Basically I want to have users enter comma separated words(incl numbers) without special characters.

I'll use it to validate tags from acts_as_taggable_on. (i don't want to be a valid tag for example.

Thanks in advance.

A: 

^([a-zA-Z0-9]+,\s*)*[a-zA-Z0-9]+$

Note that this regex doesn't match values with whitespace, so it won't match multiple words like "abc xyz, fgh qwe". It matches any amount of whitespace after commas. You might not need ^ or $ if validates_format_of tries to match the whole string, I've never used Rails so I don't know about that.

tiftik
Hi,The tags as such are actually dealt with quite nicely by the plugin. So is it possible to only allow normal characters, numbers and comma's? (in a string? and what would the regex expr. be for that?)The above regex code doesn't work. Could that be something to do with the ruby regex syntax?
A: 
^[A-Za-z0-9]+([ \t]*,[ \t]*[A-Za-z0-9]+)*$

should match a CSV line that only contains those characters, whether it's just one value or many.

Tim Pietzcker
A: 

You can always test out regular expressions at rubular, you would find that both tiftiks and Tims regular expressions work albeit with some strange edge cases with whitespace.

Tim's solution can be extended to include leading and trailing whitespace and that should then do what you want as follows :-

^\s*[A-Za-z0-9]+(\s*,\s*[A-Za-z0-9]+)*\s*$

Presumably when you have validated the input string you will want to turn it into an array of tags to iterate over. You can do this as follows :-

array_var = string_var.delete(' ').split(',')
Steve Weet
I seem to be missing something. If I take your reg. exp. and test it in rubulur it works fine. When I do the following:validates_format_of :title, :with => ^\s*[A-Za-z0-9]+(\s*,\s*[A-Za-z0-9]+)*\s*$, :message =>I get an error in my editor (doesn't like it) and I get an error when I run it in browser:syntax error, unexpected '^'...s_format_of :title, :with => ^\s*[A-Za-z0-9]+(\s*,\s*[A-Za-z...
@squids - you need to wrap the characters withn `//` like `:with => /^\s*[A-Za-z0-9]+(\s*,\s*[A-Za-z0-9]+)*\s*$/` so Ruby interprets it as a regexp
Beerlington