Rails 如何用 validates 加 validates_with 验证新浪微博昵称格式:4-24 位字符,支持中文、英文、数字、“-”、“_”

freshlhy · June 23, 2013 · Last by freshlhy replied at June 23, 2013 · 9001 hits

或者只用 validates_with,还有更好的方法没?

正则的话 /\A[\p{Han}\p{Alnum}\-_]{4,24}\z/ 就行了,但是渣浪验证的长度是转码成 gb18030 后的字节数而不是字符数...

validates :weibo_nick, length: {
  maximum: 24,
  tokenizer: lambda{|s| s.encode('gb18030').bytes }
}

#1 楼 @luikore 非常感谢 ~~~~

You need to Sign in before reply, if you don't have an account, please Sign up first.