Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 验证多个空格字符_Ruby_Ruby On Rails 3_Validation - Fatal编程技术网

Ruby 验证多个空格字符

Ruby 验证多个空格字符,ruby,ruby-on-rails-3,validation,Ruby,Ruby On Rails 3,Validation,我正在处理一个项目,其中有一个表单,如果验证失败,我需要用适当的消息进行验证 验证用于格式检查。我需要检查用户是否输入超过1个空格字符的单词。我是说 如果用户输入 "hello world" 然后它应该显示“无效格式”。正确的格式应该是 "hello world" 我的意思是只允许1个空格字符 我试过这个 validates_format_of :name, :with => /\s/ 但当没有空格字符时,它会显示错误 试试这个: validates_format_of :na

我正在处理一个项目,其中有一个表单,如果验证失败,我需要用适当的消息进行验证

验证用于格式检查。我需要检查用户是否输入超过1个空格字符的单词。我是说

如果用户输入

"hello    world"
然后它应该显示“无效格式”。正确的格式应该是

"hello world"
我的意思是只允许1个空格字符

我试过这个

validates_format_of :name, :with => /\s/
但当没有空格字符时,它会显示错误

试试这个:

validates_format_of :name, :without => /\s{2,}/, :message => "invalid format"
请注意,
\s
匹配任何空格字符,包括换行符、制表符等以及空格。如果您只想匹配两个或多个空格(而不是两个或多个空格字符),那么这会更好:

validates_format_of :name, :without => /\ {2,}/, :message => "invalid format"

感谢shioyama的努力,但它以另一种方式工作,我的意思是,当有0或1个空格时,我显示“无效格式”,而如果有超过1个空格字符,则显示“无效格式”。您确定有
而没有
而没有
而有
?我已经测试过了,它是有效的。请检查您是否有
:不带=>/\s{2,}/
和不带
:带=>/\s{2,}/
。哦。。。你是对的,shioyama,这是我的错误,它是“有”而不是“没有…”。。。。。非常感谢,在提交之前,我会用JavaScript检查表单中的输入,并去掉多个空格。另一种方法是
挤压(“”)
挤压
字符串,而不是在用户提交字符串后将其扔回去。