Validation 控制器Grails中的电子邮件验证

Validation 控制器Grails中的电子邮件验证,validation,grails,groovy,sendmail,email-validation,Validation,Grails,Groovy,Sendmail,Email Validation,我只是想在控制器中验证一个电子邮件地址,我认为这很简单。我采用的方法如下: def emailValidCheck(String emailAddress) { EmailValidator emailValidator = EmailValidator.getInstance() if (!emailAddress.isAllWhitespace() || emailAddress!=null) { String[] email = emailAddress.

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

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方法中调用。

我建议使用和来实现这一点。例如:

命令对象:

@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
    }
}

我曾经看到过一封电子邮件regex。它有4页长。邮件中的返回。每个闭包只从当前的闭包迭代中返回。@JamesKleeh-这可能只包括常见情况!新用户提示:您应该在问题中添加编程语言标签。感谢所有回复@好的,谢谢你,我还在学习。。。在“emailValidCheck”函数中,评估电子邮件的if只运行一次,例如“if(emailValidator.isValid(it))?”?那么,你是说需要某种形式的计数器来确保每个计数器都经过检查?感谢电子邮件的问题:没错,它无法识别许多新的TLD。这应该在Grails中解决。你有没有向他们报过窃听器?如果我没记错的话,Grails正在使用ApacheCommons进行电子邮件验证,因此升级就足够了。