Rails验证用户名中没有空格

yel*_*ign 14 ruby ruby-on-rails

我想验证用户名没有白色/空白区域供我的用户使用.是否有内置验证可以做到这一点?或者最好的方法是什么.似乎这是一个非常常见的要求.

MBO*_*MBO 47

我会尝试格式验证器:

validates :username, format: { with: /\A[a-zA-Z0-9]+\Z/ }
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,当您不想要用户名中的空格时,您也不需要其他字符.

或者,当您真的只需要检查空格时,请without改用:

validates :username, format: { without: /\s/ }
Run Code Online (Sandbox Code Playgroud)

完整文档:http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_format_of(与之validates ... format: {}相同validates_format_of ...)


Mur*_*foX 5

我相信你必须创建一个自定义验证器:

validate :check_empty_space

def check_empty_space
  if self.attribute.match(/\s+/)
    errors.add(:attribute, "No empty spaces please :(")
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 只是`\ s`,`+`是不必要的. (2认同)