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 例外で壊れます。なぜそれが正しく検証されず、saveメソッドで呼び出されているemailTheAttendees()メソッドにさえ入っていないのか理解できません。

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 に答える