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:
Thank you! It is really usefull for me!
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.
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})$/)
}
nice blog.. liked it very much....can someone give me some other related blog address..???neways appreciated..!!!
free find cell phone
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.
Genial brief and this fill someone in on helped me alot in my college assignement. Gratefulness you on your information.
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!!
Hey really you did a great job.... very interesting information found here... Thanks very much for the share....
:O So mush Info :O � THis Is he MOst AMAzing SIte DUDe� :D
Hello. Great job. I did not expect this on a Wednesday. This is a great story. Thanks!
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.
I don�t usually reply to posts but I will in this case. :)
yea nice Work :D
Wow! what an idea ! What a concept ! Beautiful .. Amazing � :)
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.
Hi,
This is an interesting blog post here.... I like your blog, Its amazing. Thanks for the share....
nice job...
nice blog.. liked it very much....can someone give me some other related blog address..???neways appreciated..!!
Wow! Its looking awesome.... Really its an interesting informative blog post here.... Keep posting such an amazing blog post.
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
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!
Thanks a lot for sharing this stuff. I would like to read few more articles from you.
Thanks for sharing that information. Was very interesting to read.
interesting read
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..
cool read
Thanks a lot of nice post here.....!
This won't really have success, I consider like this.
Hi! Great list! this will help me to complete my task. Thanks a lot for the share... Keep it up.
Thanks, great share.I need this article to complete my assignment in the college, and it has same topic with your article.
Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
Friends Phone Case
Great Work
iPhone 6s Plus Cases
thanks so much Buy USA Phone Numbers Online
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
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
Post a Comment