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.


class party {
String name
String workPhone

static constraints = = {

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:
* @author Jim Shingler ShinglerJim at
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()

protected void processValidate(Object target, Object propertyValue, Errors errors) {
if (validateConstraint && !validate(target, propertyValue)) {
def args = (Object[]) [constraintPropertyName, constraintOwningClass,
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.


zzkozak said...

Thank you! It is really usefull for me!

Inge 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.

Anonymous said...

Generic Viagra is the world renowned medicine for erectile dysfunction and most men have forgotten they ever had a problem with erections after its use. Take it on empty stomach and it will work in 30 minutes. Erections can be achieved on stimulation.Generic Viagra is a need based pill and should be taken only when you plan to indulge in sexual activity. Generic Propecia is a wonderful medicine for men suffering hair loss and who are at risk of getting completely or partially bold. Propecia can also help you at the beginning stages of some prostatic problems. Viagra improves erections for most men no matter how long they have had erectile dysfunction, taken approximately 30 minutes before your plan of sexual activity and works on stimulation for around 4 hours.Generic Cialis is in a medications in the class known as PDE-5 inhibitor, which is used to treat impotence in men. Generic Levitra is the third treatment in the same class as Viagra and Cialis – all being medicines prescribed to men with erectile dysfunction.

Penis Enlargement Pills said... is an all-natural Penis Enlargement, safe, and guaranteed alternative to painful and dangerous Penis enlargement methods such as surgery, straps, or rings.
penis enlargement pills or male enhancement pills will immediately boost your performance, improve your orgasms, and increase the size of your penis within just a few weeks!


best penis enlargement said...

We just wanted to share information about best penis enlargement that are busy talking about people who want a bigger penis size, stronger and able to increase stamina.
Penis Enlargement Pills
Top Penis Enlargement Pills
Method Penis Enlargement Pills

male said...

For men who want bigger, harder, longer-lasting erections, there's now VigRX Plus™, a fresh twist on the already popular VigRX™, but designed to further enhance men's sexual functioning with the addition of three exciting new ingredients: Damiana, Tribulus, and Bioperin. Doctor endorsed and rated #1 for results by clients of penis enlargement consumers. rated two penis pills is vimax. if you find about male enhancement this products is the best and proven to work, there products have money-back guarantee in effectiveness and result.

kiara said...

Costa Rica Tours
Tours Costa Rica

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....

samfar143 said...

Congratulations. Really satisfied with the quality of the data provided. I hope that you continue with the exceptional work done.
locksmith pembroke pines fl
Bayonne NJ Locksmith
Locksmith Alameda CA
San Jose locksmith
Locksmith San Jose CA
Locksmith San Jose CA
Locksmith San Jose CA
Locksmith San Jose CA
Locksmith Woodridge
Locksmith Woodridge IL
Locksmith Woodridge
Woodridge Locksmith
Locksmith Woodridge IL
Locksmith Woodridge
Locksmith Woodridge
Locksmith Woodridge IL
Locksmith Woodridge
Locksmith Woodridge
Locksmith Woodridge
Locksmith Woodridge IL
Locksmith Woodridge
Locksmith Woodridge
mesquite locksmiths
locksmith irvine ca
mesquite locksmiths
locksmith miami beach fl
locksmith aventura
mesquite locksmiths
hialeah locksmiths
mesquite locksmiths
mesquite locksmiths

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.

Ross said...

christian louboutin shoeschristian louboutin shoes
christian louboutin bootschristian louboutin boots
christian louboutin sandalschristian louboutin sandals
christian louboutin slingbackchristian louboutin slingback
christian louboutin sneakerschristian louboutin sneakers
christian louboutin wedgeschristian louboutin wedges
christian louboutin weddingchristian louboutin wedding
timberland bootstimberland boots
asics shoesasics shoes
asics running shoesasics running shoes
dsquared jeans mendsquared jeans men
dsquared shoes 2011dsquared shoes 2011
karen millen dresseskaren millen dresses
marque t shirtmarque t shirt

Alice said...

Really you have done great job,There are may person searching about that now they will find enough resources by your post.I like this blog..
Blogger how when you visit my site,
My Site created for men's health,
Here the best method for you and get the best Penis Enlargement Pills today..

buy generic viagra said...

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..!!

abercrombiefitch said...

the iconic sneaker was originally introduced on now.
Nike Air Max 2011
Nike Air Max Shoes
Nike Air Max
Nike Air Max Wildwood Supreme
Nike Air Max Turbulence
Nike Air Max Skyline
Nike Air Max Goadome
Nike Air Max Fitsole
Nike Air Max Zenyth
Nike Air Max Boots
Nike Air Max Zoom Kobe
Nike Air Max Tn
Nike Air Max LTD
Nike Air Max Presto
Nike Air Max BW
Nike Air Max 24 7
Nike Air Max 2010
Nike Air Max 2011
Nike Air Max 2009
Nike Air Max 95
Nike Air Max 91
Nike Air Max 87
Nike Air Max 180
Nike Air Max Griffey Max 1
Nike Air Max 90
Nike Air Max 1
Abercrombie and Fitch London
Abercrombie & Fitch Clothes
Vibram Shoes
Cheap Air Max
Nike Air Max Shoes
is available in a vivid array of colors, including, Jiffy Black, Pigeon Grey, Shell White, Dodger Blue, and Beaver Brown.

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

Fashionable life said...

We are dedicated to delivering the most recent and greatest high quality Christian Louboutin Heels along with other artist at Christian louboutin outlet. stroe. With this broad variety of Christian louboutin thong sandals and Christian louboutin pumps sale we are positive that you simply will possibly be in a location to come across some attractive substantial
Christian Louboutin Peep Toes for all individuals unique occasions. Christian Louboutin Heels 2011 now gets the ladies' favorite. unique design, elegant and noble style,this Christian louboutin discount shoes will possibly be your 1st choice.

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.

Sinan said...

Thanks so much for this! This is exactly what I was looking for bedava chat - islami chat - islami sohbet - sohbet siteleri - dini sohbet - mynet sohbet - sohbet odaları - garanti arkadas - sohbet kanallari - mirc sohbet - chat siteleri - mirc script indir - sohbet odaları - cinsel muhabbet - cinsel sohbet - Sex chat - seviyeli sohbet - kameralı sohbet - sohbet et - cinsel sohbet - sex sohbet - mirc - mirc indir - kameralı mirc - turkce mirc - sohbet siteleri - cet - chat kanali - chat kanalları - sohbet kanali - sohbet kanalları - Video izle - izmir sohbet - kaliteli sohbet - seviyeli chat - sesli sohbet

Nike Mercurial Vapor Superfly said...

Glad to see all the speakers, really wonderful content. Do not know if you like Nike mercurial soccer cleats or Nike soccer cleats and Nike Football Cleats,Nike Mercurial Vapor Superfly with New nike soccer shoes.

ehic card said...

interesting read

Gender selection said...

Nice ,inreresting post .. I am always looking for such post..Thanks for shareing with us.

Want a girl? Want a boy? Now it's possible! A newborn sex determination. Desire to determine the sex of the newborn. For more information about Gender selection, Natural gender selection, Determine baby gender, Holy Land gender selection, Predetermine baby's sex, please visit: .

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..

Anonymous said...

Певица голограма это круто или… вот еслибы на русском языке она пела

Благодарю за информацию действительно увлекательно, однако меня также интересуют и новости бизнеса. Надо же
развиваться в области бизнеса

новости голографии. Надо
же развиваться в области голографии

Голограмма с записью в трехмерной среде как наиболее совершенная форма изображения

Что еще может нести в себе голограмма

что голограмма

Голограмма "орел"

нужно сказать о голограммах

Голограмма представляет собой трехмерную фотографию

голограмма 15 мм

Вот перед нами голограмма яблока

Трёхмерная голограмма

Голограмма в рекламе

основана голография

Что может голография

ГОЛОГРАФИЯ — особый фотографический метод

Защитная голография

До изобретения лазеров голография практически не развивалась

получившим название голография


Перспективно применение импульсной Голография в интерферометрии

Оптическая Микроформ

голография уже перестает быть экзотикой


Такая голография называется динамической

Статья "Голография на кухне"

Голография возникла на базе двух технических наук

Голография основывается на двух физических явлениях

практическая конференция «Голография в России

ГОЛОГРАФИЯ особый фотографический метод

Любительская голография — голографические технологии

Специализированное предприятие «Голография» входит в тройку мировых лидеров по уровню технологий

Голография "на кухне" Автор

Художественная голография находится еще в начале своего пути

Изобразительная голография в Перми

Частная выставка "Мировая Голография" Игорь Осколков Анимированная Голография

holography — поляризационная голография

red kitchenaid mixer said...

interesting read

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.

John Anderson said...

Nice to be visiting your blog again, Buy Toprol Online has been months for me. Well this article that i've been waited for so long. Generic Clomid Online need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share

Ömer Konat said...

Sesli Sohbet , Sesli Chat , Kameralı Sohbet , Arkadaşlık Sitesi
Site Hakkında: Sesli Sohbet, Sesli Chat, Kameralı Sohbet Yapabileceğiniz Ücretsiz Sosyal Paylaşım Sitesidir.

John Anderson said...

Nice to be visiting your blog again, Generic Metformin has been months for me. Well this article that i've been waited for so long. Generic Ultracet need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share

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.

China tours said...

Thanks. I always enjoy reading your posts - they are always humorous and intelligent.I am a china tour lover,You can learn more: China vacation packages | China city tours | China Travel Agency

obat herbal said...

Glad to visit your site. An awesome blog. Nice Information It's really very informative that I wanted ever, thanks for this. Jual Peninggi Badan Alami Bali Ratih Obat Jerawat Obat Asam Urat AlamiKapsul Mengkudu Obat Pelangsing Badan HerbalMadu Hitam Pahit Masker Wajah Alami

Learn Chinese said...

I'm learning mandarin Chinese because I believe it's the only way to really learn about China.When I was searching for a place to learn mandarin Chinese, I called several schools. Hanbridge was the best because they had excellent teachers and a very friendly and welcoming spirit . I really appreciate the opportunity to learn here and would recommend Hanbridge to others.

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