简体   繁体   English

一个词的Rails验证

[英]rails validation for one word

I need to create a validation for field to ensure that it is only one word. 我需要为字段创建一个验证,以确保它只是一个单词。

Here is what I have, but it only validates that the length is 1 character , not one word 这是我所拥有的,但是它只验证长度是1个字符,而不是一个字

validates_length_of :name, maximum: 1, too_many_words: 'Please choose a name with only one word', tokenizer: ->(str) { str.scan(/\w+/) }

I found the example I'm working with here http://www.rubydoc.info/docs/rails/4.1.7/ActiveModel/Validations/HelperMethods:validates_length_of 我在这里找到了正在使用的示例http://www.rubydoc.info/docs/rails/4.1.7/ActiveModel/Validations/HelperMethods:validates_length_of

I actually found the answer here http://guides.rubyonrails.org/active_record_validations.html 我实际上在这里找到了答案http://guides.rubyonrails.org/active_record_validations.html

validates :name, length: {
    maximum: 1,
    tokenizer: lambda { |str| str.split(/\s+/) },
    too_long: "Please choose a name that is only %{count} word."
  }
validates :name,
              :presence => true,
              :uniqueness => true,
              :length => {
                  :maximum => 1,
                  :tokenizer => lambda {|str| str.scan(/\w+/)},
                  :too_long => "Name must be one word."
              }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM