Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails中的正则表达式验证_Ruby On Rails_Regex_Validation - Fatal编程技术网

Ruby on rails rails中的正则表达式验证

Ruby on rails rails中的正则表达式验证,ruby-on-rails,regex,validation,Ruby On Rails,Regex,Validation,我是rails的新手,我正在尝试注册我的用户名,不使用特殊字符和空格,但允许使用-符号 Example : @@Pierre! => invalid Pierre-Louis => valid Pierre Louis => invalid 在User.rb文件中,我有: class User < ApplicationRecord ... validates :first_name, presence: true, length: {maximum: 25}, fo

我是rails的新手,我正在尝试注册我的用户名,不使用特殊字符和空格,但允许使用-符号

Example : 
@@Pierre! => invalid
Pierre-Louis => valid
Pierre Louis => invalid
在User.rb文件中,我有:

class User < ApplicationRecord
...
validates :first_name, presence: true, length: {maximum: 25}, format: {with: Regexp.new('[^0-9A-Za-z-]')}
...
class用户
我没有任何错误消息,我仍然能够使用特殊字符注册

另外,如果名称未经验证,我想添加一条错误消息

你有什么线索吗


任何帮助都将不胜感激

使用正则表达式验证格式时,需要确保匹配正在验证的整个字符串。为了做到这一点,您的正则表达式需要以标记字符串开始和结束的锚点
\A
\z
开始和结束

就你而言:

validates :first_name, 
  presence: true, 
  length: {maximum: 25}, 
  format: {with: /\A[-0-9A-Za-z]\z'/}
  message: "Custom message"

假设您接受数字、大小字母和减号。

With
:message
选项: