Over a million developers have joined DZone.

Grails Goodness: Add Extra Valid Domains and Authorities for URL Validation

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Grails has a built-in URL constraint to check if a String value is a valid URL. We can use the constraint in our code to check for example that the user input http://www.mrhaki.com is valid and http://www.invalid.url is not. The basic URL validation checks the value according to standards RFC1034 and RFC1123. If want to allow other domain names, for example server names found in our internal network, we can add an extra parameter to the URL constraint. We can pass a regular expressions or a list of regular expressions for patterns that we want to allow to pass the validation. This way we can add IP addresses, domain names and even port values that are all considered valid. The regular expression is matched against the so called authority part of the URL. The authority part is a hostname, colon (:) and port number.

In the following sample code we define a simple command object with a String property address. In the constraints block we use the URL constraint. We assign a list of regular expression String values to the URL constraint. Each of the given expressions are valid authorities, we want the validation to be valid. Instead of a list of values we can also assign one value if needed. If we don't want to add extra valid authorities we can simple use the parameter true.

// Sample command object with URL constraint.
class WebAddress {
    String address

    static constraints = {
        address url: ['129.167.0.1:\\d{4}', 'mrhaki'] 

        // Or one String value if only regular expression is necessary: 
        // address url: '129.167.0.1:\\d{4}'

        // Or simple enable URL validation and don't allow
        // extra hostnames or authorities to be valid
        // address url: true
    }
}

Code written with Grails 2.2.4

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}