自定义验证不能包含空格
Custom validation cannot include spaces
在我的 Ruby on Rails 应用程序中,我使用自定义验证,并尝试使用以下代码确保字符串中没有空格:
record.errors[field] << "First name cannot include spaces" if value.gsub(/\s+/, "")
但它不起作用,就像我输入一些没有空格的文本一样,错误仍然出现,我有什么办法可以做到这一点吗?
你不想要 gsub
,而是 match
。
gsub
将 return 没有 space 的字符串,这在 Ruby.
中是真实的
match
将 return 匹配的字符串(如果存在)如果不存在则为 nil。零是假的。
record.errors[field] << "First name cannot include spaces" if value.match(/\s+/)
@evanbikes 的回答是正确的,但有一个小的语法更正(将来可能会为您省去一些麻烦):
record.errors.add(field, "First name cannot include spaces") if value.match(/\s+/)
以防 Rails 人将来选择更改用于错误的存储机制。
见http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add
在我的 Ruby on Rails 应用程序中,我使用自定义验证,并尝试使用以下代码确保字符串中没有空格:
record.errors[field] << "First name cannot include spaces" if value.gsub(/\s+/, "")
但它不起作用,就像我输入一些没有空格的文本一样,错误仍然出现,我有什么办法可以做到这一点吗?
你不想要 gsub
,而是 match
。
gsub
将 return 没有 space 的字符串,这在 Ruby.
match
将 return 匹配的字符串(如果存在)如果不存在则为 nil。零是假的。
record.errors[field] << "First name cannot include spaces" if value.match(/\s+/)
@evanbikes 的回答是正确的,但有一个小的语法更正(将来可能会为您省去一些麻烦):
record.errors.add(field, "First name cannot include spaces") if value.match(/\s+/)
以防 Rails 人将来选择更改用于错误的存储机制。
见http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add