Pergunta

I am looking for a way to validate IP addresses in Grails via constraints.

Is something like this possible?

package example

class Ip {

    String ip

    static constraints = {
        ip(unique: true, inetAddress: true)
    }
}

I have found this link: http://grails.org/doc/2.2.x/api/org/codehaus/groovy/grails/validation/routines/InetAddressValidator.html, but I don't know how to implement this.

Foi útil?

Solução

I found the solution I searched for

import org.codehaus.groovy.grails.validation.routines.InetAddressValidator

class Ip {

   String ip



 static constraints = {
    ip(blank: false, unique: true, validator: { 
         return InetAddressValidator.getInstance().isValidInet4Address(it) 
         } )
 }
}

Outras dicas

You can use a regular expression to validate the IP address format.

class Ipaddr {

    String ip_addr

    static constraints = {
        ip_addr(matches:/^([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$/)
    }
}

If you need a specific range, you can build the regex with:

IP address range tool http://support.google.com/bin/answer.py?hl=en&answer=1034771

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top