Email Validation in a controller Grails

耗尽温柔 提交于 2019-12-10 21:38:13

问题


I'm just trying to validate an email address in a Controller which I thought would be simple. The method I've done is as follows:

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

This is being used with a sendMail function, which my code for that is here:

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")
            }
        }
    }

}

This works and sends emails to valid email addresses, but if I put in something random that is not an address just breaks with sendMail exception. I can't understand why it's not validating correctly and even going into the emailTheAttendees() method ... which is being called in the save method.


回答1:


I would suggest using constraints and a command object to achieve this. Example:

Command Object:

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

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

Call it like this in your controller:

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

        // work with the command object data
    }
}


来源:https://stackoverflow.com/questions/12481619/email-validation-in-a-controller-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!