我对用户名和电子邮件有以下验证规则。
validates :username,
presence: {:message => "Please choose a username.", on: :update},
uniqueness: {:message => "Username already exisits. Please select a different one."},
length: {in: 3..15, :message => "Username should be 3-5 characters long", :allow_blank => true}
validates :email,
presence: {:message => "Please enter your Email Address."},
uniqueness: {:message => "Email Address already exisits. Please Login!"}
validate :email_regex
def email_regex
if email.present? and not email.match(/\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/)
errors.add :email, "Please enter a valid Email Address."
end
end
对于用户名:我不想允许除小字母,点,数字以外的任何内容。
我是否需要编写一个完全不同的验证邮件,例如email_regex,或者是否有一个简化的版本,我可以使用逗号添加我现有的规则,'
答案 0 :(得分:3)
您可以使用以下内容:
validates :username, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i}
为您现有的用户名验证添加逗号分隔选项格式。还有一件我错过的,这是虚拟正则表达式,你需要根据你的目的申请。