Validate ip address in Grails
Asked Answered
S

3

3

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.

Shimmery answered 10/7, 2013 at 11:56 Comment(0)
S
5

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) 
         } )
 }
}
Shimmery answered 1/8, 2013 at 15:3 Comment(0)
E
1

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

Emileemilee answered 11/7, 2013 at 18:49 Comment(2)
Thanks! But I'm more looking for a solution using the API validation routineShimmery
Hi, I've just found that the google answer is no longer online.Lorrainelorrayne
C
0

Grails 3 implements InetAddressValidator at org.grails.validation.routines.InetAddressValidator.


For Grails 4+, use Apache commons-validator:

build.gradle:

implementation 'commons-validator:commons-validator:1.7'

Ip.groovy:

import org.apache.commons.validator.routines.InetAddressValidator

class Ip {
   String ip

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

Or use regex. Example:

Constant Holder:

class RegexValidationConstants {
    private final static String IPV4_OCT = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/
    final static String IPV4 = /^${IPV4_OCT}(\.${IPV4_OCT}){3}$/.toString()
}

Ip.groovy:

class Ip {
   String ip

   static constraints = {
      ip(blank: false, unique: true, matches: RegexValidationConstants.IPV4)
    }
}
Califate answered 22/9, 2022 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.