验证多个电子邮件并处理Rails中的错误的最佳方法是什么? [英] What's the best way to validate multiple emails and handle errors in Rails?

查看:110
本文介绍了验证多个电子邮件并处理Rails中的错误的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在目前我正在建立的应用程序中,我有一个textarea,用户将输入一个逗号分隔的电子邮件地址列表。

In the current app I'm building I've got a textarea where a user will enter a comma-delimited list of email addresses.

我目前将列表分成数组,然后逐个保存。但是,如果我有这个输入...

I'm currently splitting the list into an array and then saving one by one. But if, say, I have this input...

blah@example.com,test @ example,foo@example.com

blah@example.com, test@example, foo@example.com

...然后blah@example.com将被保存,但保存test @ example将失败。所以我需要从逗号分隔的值字符串中删除blah@example.com,当我显示test @ example不是有效的电子邮件地址时,我传回给textarea。

... then blah@example.com will be saved, but saving test@example will fail. So I then need to remove blah@example.com from the comma-delimited string of values that I pass back to the textarea when I show the error that test@example isn't a valid email address.

有没有更好的方法来验证这些在服务器端,处理错误,而不会在控制器中变得丑陋/丑陋?

Is there a better way to validate these on the server side and handle errors without getting fancy / ugly in the controller?

感谢提前!

推荐答案

假设这是一个模型has_many电子邮件,电子邮件模型使用:validate_email,您可以执行以下操作:

Assuming this is a model that has_many emails, and the email model uses :validate_email, you could do something like the following:

class Foo < ActiveRecord::Base
  validate :must_not_have_invalid_addresses

  ...

  def emails=(addresses)
    @invalid_addresses = []
    addresses.split(",").each do |address|
      @invalid_addresses.push(address) unless emails.create({:address => address})
    end
  end

  def must_not_have_invalid_addresses
    errors.add_to_base("Some email addresses were invalid") unless @invalid_addresses.empty?
  end

end

这提供了验证错误+一系列无效的电子邮件地址,如果您愿意,您可以访问您的视图。

This provides a validation error + an array of the invalid email addresses which you can make accessible to your view if you like.

这篇关于验证多个电子邮件并处理Rails中的错误的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆