Validating emails, urls and date using Java API

14 / Nov / 2011 by Bhagwat Kumar 5 comments

Recently I was looking for a programmatic way for validating data against well known validation e.g. email and date. I have to use them inside custom validator and sometimes in controller/action. Creating Command objects for validating was not suitable in my case(overkilling solution). Writing/looking for regular expression was another solution. I found a special class GenericValidator in org.apache.commons.validator package (commons-validator jar file, bundled with grails jars) . The class has many useful static methods for validating data. e.g. for validating email, url, credit card, date etc. Here is the sample code for validation using GenericValidator class:

import org.apache.commons.validator.GenericValidator

assert GenericValidator.isEmail("bhagwat@intelligrape.com")  //valid email
assert !GenericValidator.isEmail("bhagwatintelligrape.com")  // invalid email

assert GenericValidator.isUrl("http://www.intelligrape.com")  //valid URL
assert !GenericValidator.isUrl("www.intelligrape.com") //invalid URL

assert GenericValidator.isCreditCard("4111111111111111") // valid visa card number
assert !GenericValidator.isCreditCard("4111111111111112") // invalid visa card number

assert GenericValidator.isDate("2011-12-30", "yyyy-MM-dd", true) // valid date(last argument for checking strict)
assert GenericValidator.isDate("2011-02-28", "yyyy-MM-dd", true) // valid date - 28th Feb
assert !GenericValidator.isDate("2011-02-29", "yyyy-MM-dd", false) // invalid date - 29th Feb 2011

For other useful methods and their details follow the link :
http://commons.apache.org/validator/apidocs/org/apache/commons/validator/GenericValidator.html.

In addition to GennericValdator class there are separate classes for validating date, email, credit card, ISBN validator in the org.apache.commons.validator package viz. DateValidator, CreditCardValidator, EmailValidator, ISBNValidator, UrlValidator and so on. Here is the sample code for using DateValidator class.

import org.apache.commons.validator.DateValidator

DateValidator dateValidator=DateValidator.getInstance()
assert dateValidator.isValid("11-02-28", "yy-MM-dd", true)
assert !dateValidator.isValid("11-02-29", "yy-MM-dd", true)

Hope it helps you.

Bhagwat Kumar
bhagwat(at)intelligrape(dot)com

FOUND THIS USEFUL? SHARE IT

comments (5)

  1. Bhagwat Kumar

    Obviously you can use built-in validations inside “static constraints” in domain/command objects. As I have mentioned clearly my situation was something different i.e. to be able to use them outside the “static constraints”.

    Reply

Leave a comment -