验证超过1个空格字符

时间:2021-05-02 19:11:48

I am working on 1 project and there is 1 form in it where i need validation with appropriate message if validation fails

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

validation is for format check. I need to check if user enter words with more than 1 space character in it. i mean

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

if user enter

如果用户输入

"hello    world"

then it should show "invalid format". The correct format should be

那么它应该显示“无效格式”。应该是正确的格式

"hello world"

I mean only 1 space character is allowed.

我的意思是只允许一个空格字符。

I have tried this

我试过这个

validates_format_of :name, :with => /\s/

but it shows error when there is no space character....

但是当没有空格字符时它会显示错误....

1 个解决方案

#1


3  

Try this:

尝试这个:

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

Note that \s matches any whitespace characters, which includes newlines, tabs, etc. as well as spaces. If you just want to match two or more spaces (and not two or more whitespace characters), then this would be better:

请注意\ s匹配任何空格字符,包括换行符,制表符等以及空格。如果您只想匹配两个或更多空格(而不是两个或更多个空格字符),那么这样会更好:

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

#1


3  

Try this:

尝试这个:

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

Note that \s matches any whitespace characters, which includes newlines, tabs, etc. as well as spaces. If you just want to match two or more spaces (and not two or more whitespace characters), then this would be better:

请注意\ s匹配任何空格字符,包括换行符,制表符等以及空格。如果您只想匹配两个或更多空格(而不是两个或更多个空格字符),那么这样会更好:

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