我正在创建一个嵌入式Ruby表单,我希望验证在开始之前允许9个字符,但是特别是以'x'开头,因此x12345678@a2z.ie将是有效的电子邮件,而12345678@a2z.ie无效。
a2z.ie是域,并且是必需的。
我有REGEX代码:x+\d{8}+@a2z.ie
我的代码是这样:
<div class="form-group">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email", :class => 'form-control', :validation => 'x+\d{8}+@a2z.ie' %>
</div>
我知道此代码是错误的,因为它仍然允许任何用户的电子邮件。
答案 0 :(得分:0)
使用电子邮件验证程序Ruby文件代替。
如果有帮助,也可以使用Devise。
在user.rb中,添加:
validates :email, :presence => true, :email => true
在模型中创建一个validators
文件夹。然后在上述文件夹中创建email_validator.rb并将其添加到其中:
(app / models / validators / email_validator.rb):
require 'mail'
class EmailValidator < ActiveModel::EachValidator
def validate_each(record,attribute,value)
begin
m = Mail::Address.new(value)
# We must check that value contains a domain, the domain has at least
# one '.' and that value is an email address
r = m.domain.present? && m.domain.match('\.') && m.address == value
s = m.domain.present? && m.domain.match('\@a2z.ie') && m.address == value
# Update 2015-Mar-24
# the :tree method was private and is no longer available.
# t = m.__send__(:tree)
# We need to dig into treetop
# A valid domain must have dot_atom_text elements size > 1
# user@localhost is excluded
# treetop must respond to domain
# We exclude valid email values like <user@localhost.com>
# Hence we use m.__send__(tree).domain
# r &&= (t.domain.dot_atom_text.elements.size > 1)
rescue
r = false
end
record.errors[attribute] << (options[:message] || "is invalid. Please enter xEMPLOYEENUMBER@a2z.ie, e.g. x12345678@a2z.ie") unless (r && s)
end
end
不是我想要的,但是有点。
参考:https://github.com/plataformatec/devise/wiki/How-to:-Use-a-custom-email-validator-with-Devise