SlideShare a Scribd company logo
1 of 27
Download to read offline
Validate!
( or fail… )
Wil de Bruin
e-mail: wil@site4u.nl
blog: https://shiftinsert.nl
Twitter: @wpdebruin
Who am I
• Wil de Bruin – Software / system engineer
• Wageningen,The Netherlands
• Graduated in Environmental Sciences
• Reseach microbiologist (1987)
• CTO – Founder Site4u (1994)
• CFML since Allaire ColdFusion 1.5
• Coldfusion training, consultancy, software development
and hosting
• Coldbox user since 2008
Agenda
• Why validate?
• Installation and configuration
• Validators and constraints
• Validation and your validation results
• Validation examples: UDF and CustomValidators
• Message replacements and internationalization (cbi18n)
• The good, the bad.. and possible improvements
Why validate?
• Database integrity rules
• Model rules
• API limitations
• Hack attempts
• Provide user-friendly validation error messages
Installation and configuration
Box install cbvalidation
Installation
Or drop cbvalidation files in your modules folder
Cbvalidation will register the following methods in handlers/views/layouts/interceptors
• Validate()
• ValidateOrFail()
• getValidationManager()
Configuration
validation = {
// manager = "models.utils.YourOwnValidationManager",
// The shared constraints for your application.
sharedConstraints = {
FormSharedMailBoxes = {
"BoxName" = {
"required"=true,
"validator” = "id:SharedMailBoxValidator",
"regex" = "^[a-zA-Z0-9_.-]+$"
},
"Password" = {
"required” = true,
"validator” = "id:PasswordValidator”
}
},
NewServerWizard = {
"Name" = {
required = true,
validator: "UniqueValidator@cborm"
},
// more constraints ….
}
}
}
Validators and
constraints
Constraint
The state of being restricted or confined within
prescribed bounds.
How to define constraints
// Define the field by name
// The contents are the constraints
fieldName1 = {
validator1 = validationData,
validator2 = validationData
},
fieldName2 = {
validator1 = validationData,
validator2 = validationData
}
Where to
define your
constraints
• In your config/Coldbox.cfc configuration file
• In your model component
• On the fly as a struct, most of the time in your handler.
Standard validators
• accepted
• alpha
• discrete
• inList
• max
• method
• min
• range
• regex
• required
• requiredIf
• requiredUnless
• sameAsNoCase
• sameAs
• size
• type
• udf
• unique
• validator
https://coldbox-validation.ortusbooks.com/overview/valid-constraints
Validation
examples
• Validate request scope (or struct) with a shared
constraint
• Validate request scope with a-la-carte constraint
• Validate model
Anatomy of a validate() call ( 1/3 )
• validate( target = rc )
• validate( target =myModel )
• validate ( target = rc, constraints = { name=“required” } )
• validate( target = rc, constraints = “mySpecialSharedConstraint” } )
• Validate( target = myModel, constraints = { name=“required” } )
Anatomy of a validate()
call ( 2/3 )
Validate arguments:
• @target An object or structure to validate
• @fieldsThe fields to validate on the target. By default, it
validates on all fields
• @constraints A structure of constraint rules or the name of the
shared constraint rules to use for validation
• @localeThe i18n locale to use for validation messages
• @excludeFieldsThe fields to exclude from the validation
• @includeFieldsThe fields to include in the validation
• @profiles If passed, a list of profile names to use for validation
constraints
Anatomy of a validate() call ( 3/3 )
• If target is not an object: convert struct to some general Object
• Find your constraints!
• Constraints param a struct() -> return constraints param
• Constraints param a string -> return shared constraints from config
• All other cases (including no constraint param) -> return constraints from target object
• Create includeFields param from profiles
• Loop over all constraints
• If there are includefields, do not process if field is not in includeFields
• If there are excludefields do not process if field is in excludeFields
• Return a result object (with all failed validations) or an empty Result object on success
• ValidateOrFail processing is simular, but throws an error on failed validations
• ValidateOrFail returns an object or a struct if validation passes
How to validate
Validate your request
Validate request collection
( populate your model )
SAVE
Validate your model
Populate your model
Validate model
SAVE
Validation
result object
• getResultMetadata()
• getFieldErrors( [field] )
• getAllErrors( [field] )
• getAllErrorsAsJSON( [field] )
• getAllErrorsAsStruct( [field] )
• getErrorCount( [field] )
• hasErrors( [field] )
• getErrors()
Validation examples
Custom messages and message replacements
The power of Method, UDF and
CustomValidators
MethodValidator
• The methodName will be called on the target object and it will pass in the
target, validationData, targetValue. It must return a boolean response: true
= pass, false = fail.
• Validation of related properties in target.
• But: no parameters passed, so limited use.
• Only one METHOD validator per field.
UDF validator
• Very flexible
• Input from validationTarget
• Input from request scope
• Very suitable for a-la-carte validation in handlers.
• Not very DRY.
Custom
validators (1/2)
• Very flexible
• Reusable
• Easy integration with other libraries, e.g java
• Syntax: fieldname = {Validator = “MyOwnValidator”}
• Or more flexible( easy to pass extra parameters and
more validators per fieldname: fieldname = {
MyOwnValidator = { someLimit=10, param=“abc”}
Custom
validators (2/2)
How to create a custom validator
• Init function (set validator name)
• getName()
• Validate()
• @validationResultThe result object of the validation
• @targetThe target object to validate on
• @fieldThe field on the target object to validate on
• @targetValueThe target value to validate
• @validationDataThe validation data the validator was
created with
• Create validation tests and return true onValidation à exit
validator
• Create arguments for error message (message, field,
ValidationType, rejectedValue, validationData)
• Add error toValidationResult and return false
Foutmeldingen in het
Nederlands
a.k.a Customizing your error messages
AND
Internationalization / cbi18n
Customizing your error messages
• customMessages by adding …Message to the constraint definition, e.g
"name" = {
required = true,
requiredMessage = “This is a custom message for {field}”
}
• Several message replacements, e.g: {targetValue}, {field} and severalValidator
specific replacements e.g {range}, {min}, {max}
• Simple cbi18n integration in a la carte constraints in handlers
"name" = {
required = true,
requiredMessage = getResource( “someMessageKey@myAlias”)
}
• Keys in resource file based on Target.Field.Validator
Limitations & future enhancements
• Old validators use strings for constraints, newer validators use structs.This breaks
custom messages for CustomValidators and some newer validators.
• It also breaks ALL translations for CustomValidators and some newer validators.
• You can’t customize default messages
• Internationalization support is very limited
• If you want to translate default messages, you have to specify it for every single constraint
definition.
• You can only specify ONE resource file for translations, so no resource aliases possible.This will
break code in other places
• You always have to specify locale = something in your validate calls
• Cbi18n should be part of cbvalidation and cbvalidation should listen to the current locale.
Thank you!
Questions
Slides: https://shiftinsert.nl/itb2020
E-mail: wil@site4u.nl
Slack: @wil-site4u
Twitter: @wpdebruin

More Related Content

Similar to cbvalidation

Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic Peopledavismr
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingOrtus Solutions, Corp
 
How to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyHow to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyClare Macrae
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticLB Denker
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation frameworksaqibsarwar
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
Managing Millions of Tests Using Databricks
Managing Millions of Tests Using DatabricksManaging Millions of Tests Using Databricks
Managing Millions of Tests Using DatabricksDatabricks
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5Tieturi Oy
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.IT Weekend
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best PracticesJitendra Zaa
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applicationssilviad74
 
Stop validating user input like a rookie
Stop validating user input like a rookieStop validating user input like a rookie
Stop validating user input like a rookieRoger Pence
 
MyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 NewsMyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 Newsos890
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
 

Similar to cbvalidation (20)

Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
How to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyHow to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ Effectively
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation framework
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Managing Millions of Tests Using Databricks
Managing Millions of Tests Using DatabricksManaging Millions of Tests Using Databricks
Managing Millions of Tests Using Databricks
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 
Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.Flexible validation with Hibernate Validator 5.x.
Flexible validation with Hibernate Validator 5.x.
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applications
 
Stop validating user input like a rookie
Stop validating user input like a rookieStop validating user input like a rookie
Stop validating user input like a rookie
 
MyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 NewsMyFaces Extensions Validator r3 News
MyFaces Extensions Validator r3 News
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
 

More from Ortus Solutions, Corp

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Secure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusionSecure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusionOrtus Solutions, Corp
 
Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023Ortus Solutions, Corp
 
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdfITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdfOrtus Solutions, Corp
 
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdfITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdfOrtus Solutions, Corp
 
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdfITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdfOrtus Solutions, Corp
 
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdfITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdfOrtus Solutions, Corp
 
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfOrtus Solutions, Corp
 
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdfITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdfOrtus Solutions, Corp
 
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdfITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdfOrtus Solutions, Corp
 
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdfITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdfOrtus Solutions, Corp
 
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdfITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdfOrtus Solutions, Corp
 
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdfITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdfOrtus Solutions, Corp
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfOrtus Solutions, Corp
 
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdfITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdfOrtus Solutions, Corp
 
ITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdfITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdfOrtus Solutions, Corp
 

More from Ortus Solutions, Corp (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Ortus Government.pdf
Ortus Government.pdfOrtus Government.pdf
Ortus Government.pdf
 
Luis Majano The Battlefield ORM
Luis Majano The Battlefield ORMLuis Majano The Battlefield ORM
Luis Majano The Battlefield ORM
 
Brad Wood - CommandBox CLI
Brad Wood - CommandBox CLI Brad Wood - CommandBox CLI
Brad Wood - CommandBox CLI
 
Secure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusionSecure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusion
 
Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023
 
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdfITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
 
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdfITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
 
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdfITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
 
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdfITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
 
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
 
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdfITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
 
ITB_2023_CBWire_v3_Grant_Copley.pdf
ITB_2023_CBWire_v3_Grant_Copley.pdfITB_2023_CBWire_v3_Grant_Copley.pdf
ITB_2023_CBWire_v3_Grant_Copley.pdf
 
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdfITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
 
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdfITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
 
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdfITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
 
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdfITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
 
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdfITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
 
ITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdfITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdf
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

cbvalidation

  • 1. Validate! ( or fail… ) Wil de Bruin e-mail: wil@site4u.nl blog: https://shiftinsert.nl Twitter: @wpdebruin
  • 2. Who am I • Wil de Bruin – Software / system engineer • Wageningen,The Netherlands • Graduated in Environmental Sciences • Reseach microbiologist (1987) • CTO – Founder Site4u (1994) • CFML since Allaire ColdFusion 1.5 • Coldfusion training, consultancy, software development and hosting • Coldbox user since 2008
  • 3. Agenda • Why validate? • Installation and configuration • Validators and constraints • Validation and your validation results • Validation examples: UDF and CustomValidators • Message replacements and internationalization (cbi18n) • The good, the bad.. and possible improvements
  • 4. Why validate? • Database integrity rules • Model rules • API limitations • Hack attempts • Provide user-friendly validation error messages
  • 5. Installation and configuration Box install cbvalidation Installation Or drop cbvalidation files in your modules folder Cbvalidation will register the following methods in handlers/views/layouts/interceptors • Validate() • ValidateOrFail() • getValidationManager()
  • 6. Configuration validation = { // manager = "models.utils.YourOwnValidationManager", // The shared constraints for your application. sharedConstraints = { FormSharedMailBoxes = { "BoxName" = { "required"=true, "validator” = "id:SharedMailBoxValidator", "regex" = "^[a-zA-Z0-9_.-]+$" }, "Password" = { "required” = true, "validator” = "id:PasswordValidator” } }, NewServerWizard = { "Name" = { required = true, validator: "UniqueValidator@cborm" }, // more constraints …. } } }
  • 8. Constraint The state of being restricted or confined within prescribed bounds.
  • 9. How to define constraints // Define the field by name // The contents are the constraints fieldName1 = { validator1 = validationData, validator2 = validationData }, fieldName2 = { validator1 = validationData, validator2 = validationData }
  • 10. Where to define your constraints • In your config/Coldbox.cfc configuration file • In your model component • On the fly as a struct, most of the time in your handler.
  • 11. Standard validators • accepted • alpha • discrete • inList • max • method • min • range • regex • required • requiredIf • requiredUnless • sameAsNoCase • sameAs • size • type • udf • unique • validator https://coldbox-validation.ortusbooks.com/overview/valid-constraints
  • 12. Validation examples • Validate request scope (or struct) with a shared constraint • Validate request scope with a-la-carte constraint • Validate model
  • 13. Anatomy of a validate() call ( 1/3 ) • validate( target = rc ) • validate( target =myModel ) • validate ( target = rc, constraints = { name=“required” } ) • validate( target = rc, constraints = “mySpecialSharedConstraint” } ) • Validate( target = myModel, constraints = { name=“required” } )
  • 14. Anatomy of a validate() call ( 2/3 ) Validate arguments: • @target An object or structure to validate • @fieldsThe fields to validate on the target. By default, it validates on all fields • @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation • @localeThe i18n locale to use for validation messages • @excludeFieldsThe fields to exclude from the validation • @includeFieldsThe fields to include in the validation • @profiles If passed, a list of profile names to use for validation constraints
  • 15. Anatomy of a validate() call ( 3/3 ) • If target is not an object: convert struct to some general Object • Find your constraints! • Constraints param a struct() -> return constraints param • Constraints param a string -> return shared constraints from config • All other cases (including no constraint param) -> return constraints from target object • Create includeFields param from profiles • Loop over all constraints • If there are includefields, do not process if field is not in includeFields • If there are excludefields do not process if field is in excludeFields • Return a result object (with all failed validations) or an empty Result object on success • ValidateOrFail processing is simular, but throws an error on failed validations • ValidateOrFail returns an object or a struct if validation passes
  • 16. How to validate Validate your request Validate request collection ( populate your model ) SAVE Validate your model Populate your model Validate model SAVE
  • 17. Validation result object • getResultMetadata() • getFieldErrors( [field] ) • getAllErrors( [field] ) • getAllErrorsAsJSON( [field] ) • getAllErrorsAsStruct( [field] ) • getErrorCount( [field] ) • hasErrors( [field] ) • getErrors()
  • 18. Validation examples Custom messages and message replacements
  • 19. The power of Method, UDF and CustomValidators
  • 20. MethodValidator • The methodName will be called on the target object and it will pass in the target, validationData, targetValue. It must return a boolean response: true = pass, false = fail. • Validation of related properties in target. • But: no parameters passed, so limited use. • Only one METHOD validator per field.
  • 21. UDF validator • Very flexible • Input from validationTarget • Input from request scope • Very suitable for a-la-carte validation in handlers. • Not very DRY.
  • 22. Custom validators (1/2) • Very flexible • Reusable • Easy integration with other libraries, e.g java • Syntax: fieldname = {Validator = “MyOwnValidator”} • Or more flexible( easy to pass extra parameters and more validators per fieldname: fieldname = { MyOwnValidator = { someLimit=10, param=“abc”}
  • 23. Custom validators (2/2) How to create a custom validator • Init function (set validator name) • getName() • Validate() • @validationResultThe result object of the validation • @targetThe target object to validate on • @fieldThe field on the target object to validate on • @targetValueThe target value to validate • @validationDataThe validation data the validator was created with • Create validation tests and return true onValidation à exit validator • Create arguments for error message (message, field, ValidationType, rejectedValue, validationData) • Add error toValidationResult and return false
  • 24. Foutmeldingen in het Nederlands a.k.a Customizing your error messages AND Internationalization / cbi18n
  • 25. Customizing your error messages • customMessages by adding …Message to the constraint definition, e.g "name" = { required = true, requiredMessage = “This is a custom message for {field}” } • Several message replacements, e.g: {targetValue}, {field} and severalValidator specific replacements e.g {range}, {min}, {max} • Simple cbi18n integration in a la carte constraints in handlers "name" = { required = true, requiredMessage = getResource( “someMessageKey@myAlias”) } • Keys in resource file based on Target.Field.Validator
  • 26. Limitations & future enhancements • Old validators use strings for constraints, newer validators use structs.This breaks custom messages for CustomValidators and some newer validators. • It also breaks ALL translations for CustomValidators and some newer validators. • You can’t customize default messages • Internationalization support is very limited • If you want to translate default messages, you have to specify it for every single constraint definition. • You can only specify ONE resource file for translations, so no resource aliases possible.This will break code in other places • You always have to specify locale = something in your validate calls • Cbi18n should be part of cbvalidation and cbvalidation should listen to the current locale.
  • 27. Thank you! Questions Slides: https://shiftinsert.nl/itb2020 E-mail: wil@site4u.nl Slack: @wil-site4u Twitter: @wpdebruin