Ruby-on-rails 如何验证 ActiveRecord 中电子邮件字段的格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13784845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:09:31  来源:igfitidea点击:

How would one validate the format of an email field in ActiveRecord?

ruby-on-railsrails-activerecord

提问by asmista

I have a User model in a Rails application which has an email field. Is there a default validation that will ensure the email is in the correct format? If not, how would I go about validating that field?

我在具有电子邮件字段的 Rails 应用程序中有一个用户模型。是否有默认验证可以确保电子邮件的格式正确?如果没有,我将如何验证该字段?

回答by Jonathan Vukovich-Tribouharet

Add in your gemfile:

在您的 gemfile 中添加:

gem 'validates_email_format_of'

and in your model:

并在您的模型中:

validates :email, email_format: { message: "doesn't look like an email address" }

Or if you don't want use a gem, use regex:

或者,如果您不想使用 gem,请使用正则表达式:

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i