Search code examples
validationgrailsgroovysendmailemail-validation

Email Validation in a controller Grails


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.


Solution

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