3

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

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

1 回答 1

3

我建议使用约束命令对象来实现这一点。例子:

命令对象:

@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
    }
}
于 2012-10-01T13:26:17.167 回答