Thursday, July 3, 2008

Phone Number Custom Constraint for Grails

Grails contains really great Validators that you can use in your constraints. But it is missing one that I need for a project I am working on, . . . There is no PhoneNumber constraint. Luckily, I ran across Geoff Lane's Post: Build a Custom Validator in Grails with a Plugin

In Chapter 2 Regular Expressions section of Beginning Groovy and Grails, we show using a regular expression to validate phone numbers. Well, now I had all of the parts required to make a PhoneNumber Custom Validator.

Usage:


class party {
String name
String workPhone

static constraints = = {
workPhone(phoneNumber:true)
}



The Constraint:


import org.codehaus.groovy.grails.validation.AbstractConstraint
import org.springframework.validation.Errors

/**
* Phone Number Constraint
*
* The phone number constraint is used to validate phone number formats
*
* Registering the Constraint.
*
* App Registration Config.groovy
*
* org.codehaus.groovy.grails.validation.ConstrainedProperty.registerNewConstraint(
* PhoneNumberConstraint.NAME, PhoneNumberConstraint.class)
*

*
* Plugin Registration MyPlugin.groovy:
*
* def doWithSpring = {
* ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.NAME, PhoneNumberConstraint.class);
* }
*

*
* This plugin is based upon the following posts:
*
* http://www.zorched.net/2008/01/25/build-a-custom-validator-in-grails-with-a-plugin/
* http://www.zorched.net/2008/01/26/custom-validators-in-grails-in-a-single-app/
*
* @author Jim Shingler ShinglerJim at gmail.com
*/
class PhoneNumberConstraint extends AbstractConstraint {

private static final String DEFAULT_MESSAGE_CODE = "default.phoneNumber.invalid.message";
public static final String NAME = "phoneNumber";

private boolean validateConstraint

public void setParameter(Object constraintParameter) {
if (!(constraintParameter instanceof Boolean))
throw new IllegalArgumentException("Parameter for constraint ["
+ NAME + "] of property ["
+ constraintPropertyName + "] of class ["
+ constraintOwningClass + "] must be a boolean value");

this.validateConstraint = ((Boolean) constraintParameter).booleanValue()
super.setParameter(constraintParameter);
}

protected void processValidate(Object target, Object propertyValue, Errors errors) {
if (validateConstraint && !validate(target, propertyValue)) {
def args = (Object[]) [constraintPropertyName, constraintOwningClass,
propertyValue]
super.rejectValue(target, errors, DEFAULT_MESSAGE_CODE,
"not." + NAME, args);
}
}

boolean supports(Class type) {
return type != null && String.class.isAssignableFrom(type);
}

String getName() {
return NAME;
}

/**
* This is where the real work is. Use a regular expression to validate
* the phone number.
*
* The core logic of the constraint is implemented as its own method to make the
* constraint easier to test.
*/
boolean validate(target, propertyValue) {
propertyValue ==~ /^[01]?\s*[\(\.-]?(\d{3})[\)\.-]?\s*(\d{3})[\.-](\d{4})$/
}
}


The real work is in the validate function.

As you can see, creating a custom constraint is really pretty easy. Just make sure that you follow the directions in the constraint class comments to register the constraint.

35 comments:

Anonymous said...

Thank you! It is really usefull for me!

Unknown said...

good article, though I don't agree with your "easy" statement :-) groovy/grails should be about non verbose code, and conventions over configuration. this is full flex java/spring code which contains A LOT of lines for a single regexp.

Anonymous said...

I didn't read your code because, well it's obvious, but I think this is what you're trying to achieve:

class party {
String name
String workPhone

static constraints = = {
workPhone(matches: /^[01]?\s*[\(\.-]?(\d{3})[\)\.-]?\s*(\d{3})[\.-](\d{4})$/)
}

jack said...

nice blog.. liked it very much....can someone give me some other related blog address..???neways appreciated..!!!


free find cell phone

Chris said...

Hi, I am also trying to figure out how to validate phone numbers and stumbled upon your blog post. It looks like the regex pattern you're using doesn't work if someone just types in their phone number with no additional punctuation or separators. For instance 2123832210 and 12123832210 both fail the validation, even though they are valid phone numbers.

I am working on an alternate approach, basically a phone number scrubber. Strip away all the non-digits, validate just the numbers and format using a standard ?? (???) ???-???? format or something similar.

Anonymous said...

Genial brief and this fill someone in on helped me alot in my college assignement. Gratefulness you on your information.

buy kamagra online said...

I have always felt that blogging has been an art where people express their experiences in the best manner.This is something that is very informational.Thanks for sharing!!

online generic viagra said...

Hey really you did a great job.... very interesting information found here... Thanks very much for the share....

Warren Anton said...

:O So mush Info :O � THis Is he MOst AMAzing SIte DUDe� :D

Fredric Wiley said...

Hello. Great job. I did not expect this on a Wednesday. This is a great story. Thanks!

Besa Lighting Wall Sconce said...

It sounds like you're creating problems yourself by trying to solve this issue instead of looking at why their is a problem in the first place.

Chinese Laundry Whirl said...

I don�t usually reply to posts but I will in this case. :)

Besa Lighting 943182 Series 943 Graphite Wall Sconce said...

yea nice Work :D

Chinese Laundry Womens Flat said...

Wow! what an idea ! What a concept ! Beautiful .. Amazing � :)

cachcach kids Dress said...

It sounds like you're creating problems yourself by trying to solve this issue instead of looking at why their is a problem in the first place.

buy generic viagra said...

Hi,
This is an interesting blog post here.... I like your blog, Its amazing. Thanks for the share....

Invertir en oro said...

nice job...

Inversiones en petroleo said...

nice blog.. liked it very much....can someone give me some other related blog address..???neways appreciated..!!

Inversiones en oro said...

Wow! Its looking awesome.... Really its an interesting informative blog post here.... Keep posting such an amazing blog post.

penis pills said...

Pretty excellent article. I just stumbled upon your website and wanted to say that I have genuinely liked reading your blog site posts. Any way I’ll be subscribing to your feed and I hope you post again soon. My best regards,

penis pills

cialis 20mg said...

Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!

buy valium no rx said...

Thanks a lot for sharing this stuff. I would like to read few more articles from you.

Levitra Generika kaufen said...

Thanks for sharing that information. Was very interesting to read.

ehic card said...

interesting read

inversiones en oro said...

Wow, nice post,there are many person searching about that now they will find enough resources by your post.Thank you for sharing to us.Please one more post about that..

feathered hair extensions said...

cool read

Viagra said...

Thanks a lot of nice post here.....!

the sex toys said...

This won't really have success, I consider like this.

Hotel wisconsin milwaukee said...

Hi! Great list! this will help me to complete my task. Thanks a lot for the share... Keep it up.

sports handicapping services said...

Thanks, great share.I need this article to complete my assignment in the college, and it has same topic with your article.

Kabir said...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.



Friends Phone Case

Unknown said...

Great Work
iPhone 6s Plus Cases

John said...

thanks so much Buy USA Phone Numbers Online

Anonymous said...

Thank you for sharing such an amazing article.
To buy a Customized Dc Comic, Harry potter, Couple, Friends Glass mobile cases in india
visit: Glass Mobile Cases

Anonymous said...

Thanks for sharing informative post
Drip wear provides you the best customize BFF phone covers & BFF phone cases, so what are you waiting for visit our website