SlideShare a Scribd company logo
1 of 18
Custom
Validation
What is validation ?
● Business rules that constrain the valid values of a particular property in a
domain class
● Forexample
- A Person must never have an age that islessthan zero
- Rules like these should be expressed clearly, and in only one place
Limitation to built-in validators
Itisimpossible to foresee every feasibledomain
model and every specific kind of validation that
an application might need
Limitation to built-in validators Cont...
• Forexample, Let'sconsider the case withPassword validator:
− should be minimum of specified length
− should not contain any field from personal information(name, email, date
of birth, contactno. etc)
− should use mix of alphabets, digits and special characters( a-z A-Z0-9
$#@^&*)
− confirm password fieldmust match
Limitation to built-in validators Cont...
• Customerrormessagedepending ontheinvalid data entered.
− Password must be 8 characters long
− Password should not containyour name
− confirm password do not match
− Weak password, use digits andspecial characters.
Example 1 (Built-in Validator)
class Employee{
String name
static constraint ={
name(blank:false)
}
}
Using Custom Validator
class Employee{
String name
static constraint ={
Name(
validator:{
//closure with one,two or three parameter
//return value determines thevalidation
//null or true to indicate that the value isvalid
// false to indicate an invalid value
}
)
}
}
Validator Closure parameter
• A single or no parameter block receives the value
• A two-parameter block receives the value and object reference
• A three-parameter Closure receives the value, object reference and the
errorsobject
One Parameter Closure
class User{
Stringlogin
static constraints ={
login(validator: {
// itcontains new value for login field
println propertyName
if (!it.startsWith('boba'))
return['invalid.bountyhunter']
})
}
}
Two Parameter Closure
class User {
String login
Stringpassword
static constraints ={
password(validator: {newValue, obj ->
println newValue
println obj.class.name
println obj.properties['login']
if
(obj.properties['login'].contains(newValue
))
return 'Error:Password contains login name'
})
}
}
Three Parameter Closure
class User {
String login
Stringpassword
static constraints ={
password(validator: {newValue, obj,err
->
printlnnewValue
//entered value for password
println obj.class.name //User
println obj.properties['login'] //entered value
forlogin
printlnerr
if
(obj.properties['login'].contains(newValue
))
return 'Error:Password contains login name'
})
}
}
Validator Closure return value
• Null or true to indicate that the value isvalid
• False to indicate an invalid value and use the default
message code
Validator Closure return value Cont...
• A string to indicate the error code to append to the
"classname.propertName." string used to resolve the error message. Ifa
field specific message cannot be resolved, the error code itself will be
resolved allowing for global error messages
• A listcontaining a string as above, and then any number of arguments
following it, which can be used as formatted message arguments
indexed at 3 onwards. See grails-app/i18n/message.properties to see
how the default error message codes use the arguments
Custom Error Message
• Error messages can bedefined in grails-app/i18n/message.properties
file in the following format :
errorcode=error message
• e.g.
custom.error=Error occured, property={0} class= {1}value= {2}arg1={3}
• Now you can return any of these error code whose corresponding error
message wil be rendered on views(<g:hasError....tag)
Custom Error Message Cont...
• Inerror messages you can use the following arguments that are passed
automatically:
−{0}for propertyName e.g. Login
− {1}forDomain class name e.g. class Employee
− {2}forvalue entered for the validation field
− {3}for 1st argument you pass along with errorcode
−{4}for 2nd argument you pass with errorcode
And soon
Example with Custom Error
class User {
String userId
String password
Stringpassword2
static transients =['password2']
static constraints ={
password(blank: false, nullable: false,size:5..20, validator:
{password, obj->
def password2 =obj.properties['password2']
if(password2 ==null) return true /*skip matching password
validation(only important when setting/resetting pass) */
password2 ==password ? true :
['invalid.matchingpasswords']
})
}
}
Contact us
Our Office
Client
Location
Click Here To Know More!
Have more queries on Grails?
Talk to our GRAILS experts
Now!
Talk To Our Experts
Here's how the world's
biggest Grails team is
building enterprise
applications on Grails!

More Related Content

Viewers also liked

Their most famous piece and why it was well know
Their most famous piece and why it was well knowTheir most famous piece and why it was well know
Their most famous piece and why it was well knowsathma
 
Dipsia & uria
Dipsia &  uriaDipsia &  uria
Dipsia & uriaarivera79
 
American Revolutionary War Heroes
American Revolutionary War HeroesAmerican Revolutionary War Heroes
American Revolutionary War HeroesSharon Matney
 
Final presentation
Final presentationFinal presentation
Final presentationmarshall
 
In digital space no one can hear you scream
In digital space no one can hear you screamIn digital space no one can hear you scream
In digital space no one can hear you screamJohn Watton
 
eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...
eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...
eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...John Watton
 
Isidorey Technical Introduction
Isidorey Technical IntroductionIsidorey Technical Introduction
Isidorey Technical Introductionkyleroche
 
FUKUYAMA BASE WORKSHOP Vol13 Theme
FUKUYAMA BASE WORKSHOP Vol13 ThemeFUKUYAMA BASE WORKSHOP Vol13 Theme
FUKUYAMA BASE WORKSHOP Vol13 Themenoteproject
 
FUKUYAMA BASE WORKSHOP Vol17 Theme
FUKUYAMA BASE WORKSHOP Vol17 ThemeFUKUYAMA BASE WORKSHOP Vol17 Theme
FUKUYAMA BASE WORKSHOP Vol17 Themenoteproject
 
Type1 diabetes psa_storyboard
Type1 diabetes psa_storyboardType1 diabetes psa_storyboard
Type1 diabetes psa_storyboardSharon Matney
 
Corporate Training Programs
Corporate Training ProgramsCorporate Training Programs
Corporate Training Programsfinberry academy
 
Open Day Presentation
Open Day Presentation Open Day Presentation
Open Day Presentation sallyross
 
FUKUYAMA BASE Workshop Vol.09 Theme
FUKUYAMA BASE Workshop Vol.09 ThemeFUKUYAMA BASE Workshop Vol.09 Theme
FUKUYAMA BASE Workshop Vol.09 Themenoteproject
 

Viewers also liked (17)

Their most famous piece and why it was well know
Their most famous piece and why it was well knowTheir most famous piece and why it was well know
Their most famous piece and why it was well know
 
Dipsia & uria
Dipsia &  uriaDipsia &  uria
Dipsia & uria
 
American Revolutionary War Heroes
American Revolutionary War HeroesAmerican Revolutionary War Heroes
American Revolutionary War Heroes
 
Final presentation
Final presentationFinal presentation
Final presentation
 
In digital space no one can hear you scream
In digital space no one can hear you screamIn digital space no one can hear you scream
In digital space no one can hear you scream
 
eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...
eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...
eCommerce Expo 2013 : Behavioural Marketing or How to get your customers to l...
 
Posters for presentations
Posters for presentationsPosters for presentations
Posters for presentations
 
Isidorey Technical Introduction
Isidorey Technical IntroductionIsidorey Technical Introduction
Isidorey Technical Introduction
 
FUKUYAMA BASE WORKSHOP Vol13 Theme
FUKUYAMA BASE WORKSHOP Vol13 ThemeFUKUYAMA BASE WORKSHOP Vol13 Theme
FUKUYAMA BASE WORKSHOP Vol13 Theme
 
FUKUYAMA BASE WORKSHOP Vol17 Theme
FUKUYAMA BASE WORKSHOP Vol17 ThemeFUKUYAMA BASE WORKSHOP Vol17 Theme
FUKUYAMA BASE WORKSHOP Vol17 Theme
 
Wahl user interviews
Wahl user interviewsWahl user interviews
Wahl user interviews
 
Type1 diabetes psa_storyboard
Type1 diabetes psa_storyboardType1 diabetes psa_storyboard
Type1 diabetes psa_storyboard
 
Corporate Training Programs
Corporate Training ProgramsCorporate Training Programs
Corporate Training Programs
 
Open Day Presentation
Open Day Presentation Open Day Presentation
Open Day Presentation
 
FUKUYAMA BASE Workshop Vol.09 Theme
FUKUYAMA BASE Workshop Vol.09 ThemeFUKUYAMA BASE Workshop Vol.09 Theme
FUKUYAMA BASE Workshop Vol.09 Theme
 
AWS CodeDeploy
AWS CodeDeployAWS CodeDeploy
AWS CodeDeploy
 
Isp
IspIsp
Isp
 

More from TO THE NEW | Technology

10 Best Node.js Practices you Need to Know!
10 Best Node.js Practices you Need to Know!10 Best Node.js Practices you Need to Know!
10 Best Node.js Practices you Need to Know!TO THE NEW | Technology
 
10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:TO THE NEW | Technology
 
12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective CTO THE NEW | Technology
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptTO THE NEW | Technology
 
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape SoftwareTO THE NEW | Technology
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlTO THE NEW | Technology
 
BigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearchBigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearchTO THE NEW | Technology
 

More from TO THE NEW | Technology (20)

10 Best Node.js Practices you Need to Know!
10 Best Node.js Practices you Need to Know!10 Best Node.js Practices you Need to Know!
10 Best Node.js Practices you Need to Know!
 
10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:10 Pragmatic UX techniques for building smarter products:
10 Pragmatic UX techniques for building smarter products:
 
12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C12 Key points which make Swift more effective than Objective C
12 Key points which make Swift more effective than Objective C
 
Gulp - The Streaming Build System
Gulp - The Streaming Build SystemGulp - The Streaming Build System
Gulp - The Streaming Build System
 
Grails Spring Boot
Grails Spring BootGrails Spring Boot
Grails Spring Boot
 
AWS Elastic Beanstalk
AWS Elastic BeanstalkAWS Elastic Beanstalk
AWS Elastic Beanstalk
 
Content migration to AEM
Content migration to AEMContent migration to AEM
Content migration to AEM
 
Big Data Expertise
Big Data ExpertiseBig Data Expertise
Big Data Expertise
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScript
 
Object Oriented JavaScript - II
Object Oriented JavaScript - IIObject Oriented JavaScript - II
Object Oriented JavaScript - II
 
MongoDb and NoSQL
MongoDb and NoSQLMongoDb and NoSQL
MongoDb and NoSQL
 
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
(AWS) Auto Scaling : Evening Session by Amazon and IntelliGrape Software
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
 
Cloud Formation
Cloud FormationCloud Formation
Cloud Formation
 
BigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearchBigData Search Simplified with ElasticSearch
BigData Search Simplified with ElasticSearch
 
JULY IN GRAILS
JULY IN GRAILSJULY IN GRAILS
JULY IN GRAILS
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Getting groovier-with-vertx
Getting groovier-with-vertxGetting groovier-with-vertx
Getting groovier-with-vertx
 
Introduction to Kanban
Introduction to KanbanIntroduction to Kanban
Introduction to Kanban
 
Introduction to Heroku
Introduction to HerokuIntroduction to Heroku
Introduction to Heroku
 

Recently uploaded

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Recently uploaded (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Grails Custom Validation

  • 1.
  • 3. What is validation ? ● Business rules that constrain the valid values of a particular property in a domain class ● Forexample - A Person must never have an age that islessthan zero - Rules like these should be expressed clearly, and in only one place
  • 4. Limitation to built-in validators Itisimpossible to foresee every feasibledomain model and every specific kind of validation that an application might need
  • 5. Limitation to built-in validators Cont... • Forexample, Let'sconsider the case withPassword validator: − should be minimum of specified length − should not contain any field from personal information(name, email, date of birth, contactno. etc) − should use mix of alphabets, digits and special characters( a-z A-Z0-9 $#@^&*) − confirm password fieldmust match
  • 6. Limitation to built-in validators Cont... • Customerrormessagedepending ontheinvalid data entered. − Password must be 8 characters long − Password should not containyour name − confirm password do not match − Weak password, use digits andspecial characters.
  • 7. Example 1 (Built-in Validator) class Employee{ String name static constraint ={ name(blank:false) } }
  • 8. Using Custom Validator class Employee{ String name static constraint ={ Name( validator:{ //closure with one,two or three parameter //return value determines thevalidation //null or true to indicate that the value isvalid // false to indicate an invalid value } ) } }
  • 9. Validator Closure parameter • A single or no parameter block receives the value • A two-parameter block receives the value and object reference • A three-parameter Closure receives the value, object reference and the errorsobject
  • 10. One Parameter Closure class User{ Stringlogin static constraints ={ login(validator: { // itcontains new value for login field println propertyName if (!it.startsWith('boba')) return['invalid.bountyhunter'] }) } }
  • 11. Two Parameter Closure class User { String login Stringpassword static constraints ={ password(validator: {newValue, obj -> println newValue println obj.class.name println obj.properties['login'] if (obj.properties['login'].contains(newValue )) return 'Error:Password contains login name' }) } }
  • 12. Three Parameter Closure class User { String login Stringpassword static constraints ={ password(validator: {newValue, obj,err -> printlnnewValue //entered value for password println obj.class.name //User println obj.properties['login'] //entered value forlogin printlnerr if (obj.properties['login'].contains(newValue )) return 'Error:Password contains login name' }) } }
  • 13. Validator Closure return value • Null or true to indicate that the value isvalid • False to indicate an invalid value and use the default message code
  • 14. Validator Closure return value Cont... • A string to indicate the error code to append to the "classname.propertName." string used to resolve the error message. Ifa field specific message cannot be resolved, the error code itself will be resolved allowing for global error messages • A listcontaining a string as above, and then any number of arguments following it, which can be used as formatted message arguments indexed at 3 onwards. See grails-app/i18n/message.properties to see how the default error message codes use the arguments
  • 15. Custom Error Message • Error messages can bedefined in grails-app/i18n/message.properties file in the following format : errorcode=error message • e.g. custom.error=Error occured, property={0} class= {1}value= {2}arg1={3} • Now you can return any of these error code whose corresponding error message wil be rendered on views(<g:hasError....tag)
  • 16. Custom Error Message Cont... • Inerror messages you can use the following arguments that are passed automatically: −{0}for propertyName e.g. Login − {1}forDomain class name e.g. class Employee − {2}forvalue entered for the validation field − {3}for 1st argument you pass along with errorcode −{4}for 2nd argument you pass with errorcode And soon
  • 17. Example with Custom Error class User { String userId String password Stringpassword2 static transients =['password2'] static constraints ={ password(blank: false, nullable: false,size:5..20, validator: {password, obj-> def password2 =obj.properties['password2'] if(password2 ==null) return true /*skip matching password validation(only important when setting/resetting pass) */ password2 ==password ? true : ['invalid.matchingpasswords'] }) } }
  • 18. Contact us Our Office Client Location Click Here To Know More! Have more queries on Grails? Talk to our GRAILS experts Now! Talk To Our Experts Here's how the world's biggest Grails team is building enterprise applications on Grails!