Regex Rails 4表单验证正则表达式(标题、正文)

Regex Rails 4表单验证正则表达式(标题、正文),regex,forms,validation,ruby-on-rails-4,Regex,Forms,Validation,Ruby On Rails 4,试图验证micropost表单的标题和正文。我已经想了一天了。越来越私人化了……:) 我对Rails(1.5个月)和regex(1天)都是新手 对于标题:我希望允许UTF-8字符和空格 对于正文:我想允许UTF-8字符、空格和标点符号 (ruby v 2.1.5)告诉我这一切都会好起来: /[[:space:]]*[[:alpha:]]*/ /[[:alpha:]]*[[:space:]]*/ 但当我尝试这个: validates :title, presence: true, length:

试图验证micropost表单的标题和正文。我已经想了一天了。越来越私人化了……:)

我对Rails(1.5个月)和regex(1天)都是新手

对于标题:我希望允许UTF-8字符和空格 对于正文:我想允许UTF-8字符、空格和标点符号

(ruby v 2.1.5)告诉我这一切都会好起来:

/[[:space:]]*[[:alpha:]]*/
/[[:alpha:]]*[[:space:]]*/
但当我尝试这个:

validates :title, presence: true, length: { minimum: 10, maximum: 60 }, format: { with: /[[:alpha:]]*[[:space:]]*/, message: "only letters" }
它允许像这样的数字和字符+!%/=(滑过

以下操作也失败。它不允许使用空格-至少当我包含数字或其他奇怪字符时会出错:

format: { with: /\A[[:alpha:]]*[[:space:]]*\z/, message: "only letters" }
我也尝试过做类似的事情,但没有什么区别,也失败了:

REGEX = ........
format: { with: REGEX, message: "only letters" }
这些措施也失败了:

format: { with: /\A[\p{L}\ ]\z/
format: { with: /[\p{L}\ ]/
提前谢谢

编辑 我的模型想法.rb

class Idea < ActiveRecord::Base
belongs_to :user
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
attr_reader :tag_tokens
acts_as_likeable
has_many :likes, foreign_key: :likeable_id
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :title, presence: true, length: { minimum: 10, maximum: 60 }, format: { with: /[[:alpha:]]|[[:space:]]/, message: 'only letters'}
validates :intro, presence: true, length: { minimum: 60, maximum: 160 }
validates :tag_ids, presence: true
....
private
def idea_params
params.require(:idea).permit(:title, :intro, :content, :user_id, :name)
end
end
这不允许空间:

/\A([[:alpha:]]|[[:space:]]+)\z/
这允许空间,但也允许数字:

/([[:alpha:]]|[[:space:]]+)/
也接受数字:

/(\p{L}+)/
/[\p{L}\s]+/

我从

为我工作

# /[[:alpha:]]|[[:space:]]/
class Selection
  include Mongoid::Document
  field :name, type: String
  validates :name, presence: true, format: { with: /[[:alpha:]]|[[:space:]]/, message: 'only letters'}
end
但是,当您使用presence选项时,这意味着您不能只有空格

您可以使用

~

解决办法是:

/\A[\p{L}\s]+\z/
它接受任何unicode(UTF-8)字母和任意数量的空格,但不接受单词中任何地方或单词本身的数字或其他字符(例如:%/=()+!)


最后…:)

谢谢@farhatmihalko,不幸的是,在我的模型中使用它仍然不起作用:验证:标题,状态:true,长度:{最小值:10,最大值:60},格式:{with://[:alpha:].[:space:]/,消息:'only letters'},但是您是否重新确认将您在我的模型中编写的上述所有代码都放进去了?这将引发其他问题:我将如何处理我的原始行?您的代码段在model中的位置是什么?我在开发中使用sqlite,在生产中使用postgredb-那么我将如何更改您的第二行?@Zsolt您可以提供您的模型吗?Sure@farhatmihalko编辑了原始问题,添加了模型。
/\A[\p{L}\s]+\z/