我只是想在Controller中验证一个我认为很简单的电子邮件地址。我所做的方法如下:
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方法中调用的。
答案 0 :(得分:3)
我建议使用constraints和a 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
}
}