4/25/2014

Grails domain URL validation

I've been using Grails framework for about 3 years and over the time, together with my colleagues, we've come up with many simple workarounds for common problems. One of them is URLs validation in domain classes.
Many webapps let their users store some internet addresses and then render links somewhere in the application (e.g. "my home page" link in user's profile page, etc.). It's important to make things easy for your users, and default Grails' url validator might annoy in this case. It checks if given url is syntactically valid, but it accepts only complete urls including the scheme part (e.g. http://). It's fine when the user copy-pastes the link into the input text field, because it usually contains the scheme, but sometimes people type the url manually (because it's short) and then, most of the time it's just like '77dev.com' and validator will reject it. How to avoid that?
Marcin Świerczyński tweeted today about his Grails plugin covering that problem - http://grails.org/plugin/url-without-scheme-validator. Under the hood, it still uses the default url validator, but prepends the value with 'http://' part if it's missing, and thanks to that, validation will pass.
Before such plugin was created, I've been dealing with this situation in even simpler way.
It intercepts validation of objects, and before it's done, it does the same as mentioned plugin - prepends the value with 'http://' when no '://' was found there. The difference here is that it actually stores the modified version of url in the domain objects which is better for future usage.
Example:
 
In case when the href attribute is '77dev.com', the link might redirect to an address like 'http://mywebsite.com/77dev.com' which is obviously incorrect. Using my approach, the homepageUrl field value will always contain the scheme part (either given by user, or default one if it's missing), so the href attribute will always begin with scheme, and the link will always work properly.