【问题标题】:Email Validation in a controller Grails控制器中的电子邮件验证 Grails
【发布时间】:2012-09-10 23:44:25
【问题描述】:

我只是想验证控制器中的电子邮件地址,我认为这很简单。我做的方法如下:

def emailValidCheck(String emailAddress)  {
    EmailValidator emailValidator = EmailValidator.getInstance()
    if (!emailAddress.isAllWhitespace() || emailAddress!=null) {
        String[] email = emailAddress.replaceAll("//s+","").split(",")
        email.each {
            if (emailValidator.isValid(it)) {
            return true
            }else {return false}
        }
    }
}

这与 sendMail 函数一起使用,我的代码在这里:

def emailTheAttendees(String email) {
    def user = lookupPerson()
    if (!email.isEmpty()) {
        def splitEmails = email.replaceAll("//s+","").split(",")
        splitEmails.each {
            def String currentEmail = it
            sendMail {
                to currentEmail
                System.out.println("what's in to address:"+ currentEmail)
                subject "Your Friend ${user.username} has invited you as a task attendee"
                html g.render(template:"/emails/Attendees")
            }
        }
    }

}

这可以正常工作并将电子邮件发送到有效的电子邮件地址,但如果我随机放入不是地址的东西,则会因 sendMail 异常而中断。我不明白为什么它没有正确验证,甚至进入 emailTheAttendees() 方法...在 save 方法中被调用。

【问题讨论】:

  • 我曾经看过一个电子邮件正则表达式。大概有 4 页长。
  • email.each 闭包中的返回仅从闭包的当前迭代返回。
  • @JamesKleeh - 这可能只涵盖了常见案例!
  • 新用户提示:您应该在问题中添加编程语言标签。
  • 感谢大家的回复! @wwwclaes 好的,谢谢你,我还在学习......在'emailValidCheck'功能中,如果评估电子邮件只运行一次,例如'如果 (emailValidator.isValid(it))' ?所以你是说需要某种形式的计数器来确保每一个都经过检查?谢谢

标签: validation grails groovy sendmail email-validation


【解决方案1】:

我建议使用constraintsa command object 来实现这一点。示例:

命令对象:

@grails.validation.Validateable
class YourCommand {
    String email
    String otherStuffYouWantToValidate

    static constraints = {
        email(blank: false, email: true)
        ...
    }
}

在你的控制器中这样调用它:

class YourController {
    def yourAction(YourCommand command) {
        if (command.hasErrors()) {
            // handle errors
            return
        }

        // work with the command object data
    }
}

【讨论】:

  • email:true 的问题在于它无法识别许多新的 tld。
  • 那应该在 Grails 中解决。您是否向他们提交了错误?如果我没记错的话,Grails 使用 apache commons 进行电子邮件验证,所以升级就足够了。
猜你喜欢
  • 2014-04-16
  • 2016-12-27
  • 1970-01-01
  • 2018-04-19
  • 2016-12-08
  • 2013-08-21
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多