- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Determines whether a specific key is present in a structure.
Returns
"YES", if key is in structure, otherwise "NO".
Category
Syntax
StructKeyExists(structure, "key")
See also
Structure functions; Structure functions in the Developing ColdFusion Applications
Parameters
Parameter |
Description |
|---|---|
structure |
The structure to test. |
key |
Key to test. |
Example
<cfscript>
myStruct=StructNew();
myStruct = {a:1,b=2,c=3,d=4,e=5};
ifKeyExists=StructKeyExists(myStruct,"c"); //Returns Yes since key "c" exists
WriteOutput(ifKeyExists & "|");
ifKeyNotExist=StructKeyExists(myStruct,"f"); //Returns No since key "f" does not exist
WriteOutput(ifKeyNotExist);
</cfscript>
Output
YES | NO
Using member function
<cfscript>
myStruct = {a:1,b=2,c=3,d=4,e=5};
myKeyExists=myStruct.keyExists("e");
WriteOutput(myKeyExists);
</cfscript>
Output
Does the struct key exist: YES
Real-world uses of the StructKeyExists function
API response validation- Payment processing
An eCommerce platform integrates with multiple payment gateways including Stripe, PayPal, and Square to provide customers with flexible payment options. Each payment gateway returns response data in different JSON structures with varying field names and nesting levels, creating challenges for consistent payment processing.
How it helps:
- Single validation system handles all payment gateway formats
- Safe key checking eliminates crashes from missing response fields
- Consistent extraction of transaction data regardless of source format
- Graceful handling of incomplete responses with detailed error reporting
<cfscript>
writeOutput("<h2>💳 USE CASE 1: API Response Validation - Payment Processing</h2>");
writeOutput("<h3>Business Context:</h3>");
writeOutput("<p>An e-commerce platform integrates with multiple payment gateways (Stripe, PayPal, Square). Each API returns different response structures, and the application must safely validate response data before processing orders.</p>");
// Simulate different payment gateway responses
stripeResponse = {
"id": "ch_1234567890",
"object": "charge",
"amount": 2500,
"currency": "usd",
"status": "succeeded",
"metadata": {
"order_id": "ORD-2024-001",
"customer_email": "customer@example.com"
}
};
paypalResponse = {
"id": "PAYID-ABC123",
"status": "COMPLETED",
"amount": {
"total": "25.00",
"currency": "USD"
},
"payer": {
"email_address": "customer@example.com"
}
};
squareResponse = {
"payment": {
"id": "sq_payment_123",
"status": "COMPLETED",
"amount_money": {
"amount": 2500,
"currency": "USD"
}
}
};
writeOutput("<h4>🔧 Payment Response Processing Function:</h4>");
function processPaymentResponse(response, gateway) {
result = {
success: false,
transactionId: "",
amount: 0,
currency: "",
status: "",
customerEmail: "",
errors: []
};
try {
// Stripe payment validation
if (gateway == "stripe") {
if (StructKeyExists(response, "id")) {
result.transactionId = response.id;
} else {
arrayAppend(result.errors, "Missing transaction ID in Stripe response");
}
if (StructKeyExists(response, "amount")) {
result.amount = response.amount / 100; // Stripe uses cents
} else {
arrayAppend(result.errors, "Missing amount in Stripe response");
}
if (StructKeyExists(response, "currency")) {
result.currency = uCase(response.currency);
}
if (StructKeyExists(response, "status")) {
result.status = response.status;
result.success = (response.status == "succeeded");
}
// Check for metadata with customer info
if (StructKeyExists(response, "metadata") && StructKeyExists(response.metadata, "customer_email")) {
result.customerEmail = response.metadata.customer_email;
}
}
// PayPal payment validation
else if (gateway == "paypal") {
if (StructKeyExists(response, "id")) {
result.transactionId = response.id;
} else {
arrayAppend(result.errors, "Missing transaction ID in PayPal response");
}
if (StructKeyExists(response, "amount") && StructKeyExists(response.amount, "total")) {
result.amount = val(response.amount.total);
} else {
arrayAppend(result.errors, "Missing amount in PayPal response");
}
if (StructKeyExists(response, "amount") && StructKeyExists(response.amount, "currency")) {
result.currency = response.amount.currency;
}
if (StructKeyExists(response, "status")) {
result.status = response.status;
result.success = (response.status == "COMPLETED");
}
if (StructKeyExists(response, "payer") && StructKeyExists(response.payer, "email_address")) {
result.customerEmail = response.payer.email_address;
}
}
// Square payment validation
else if (gateway == "square") {
if (StructKeyExists(response, "payment")) {
payment = response.payment;
if (StructKeyExists(payment, "id")) {
result.transactionId = payment.id;
} else {
arrayAppend(result.errors, "Missing payment ID in Square response");
}
if (StructKeyExists(payment, "amount_money")) {
if (StructKeyExists(payment.amount_money, "amount")) {
result.amount = payment.amount_money.amount / 100; // Square uses cents
}
if (StructKeyExists(payment.amount_money, "currency")) {
result.currency = payment.amount_money.currency;
}
}
if (StructKeyExists(payment, "status")) {
result.status = payment.status;
result.success = (payment.status == "COMPLETED");
}
} else {
arrayAppend(result.errors, "Missing payment object in Square response");
}
}
} catch (any e) {
arrayAppend(result.errors, "Error processing payment response: " & e.message);
}
return result;
}
// Test payment processing with different gateways
writeOutput("<h4>💰 Payment Processing Results:</h4>");
writeOutput("<table border='1' cellpadding='8' style='width: 100%;'>");
writeOutput("<tr><th>Gateway</th><th>Transaction ID</th><th>Amount</th><th>Status</th><th>Success</th><th>Errors</th></tr>");
gateways = [
{name: "stripe", response: stripeResponse},
{name: "paypal", response: paypalResponse},
{name: "square", response: squareResponse}
];
for (gateway in gateways) {
paymentResult = processPaymentResponse(gateway.response, gateway.name);
errorText = arrayLen(paymentResult.errors) > 0 ? arrayToList(paymentResult.errors, "; ") : "None";
successColor = paymentResult.success ? "green" : "red";
writeOutput("<tr>");
writeOutput("<td><strong>" & uCase(gateway.name) & "</strong></td>");
writeOutput("<td>" & paymentResult.transactionId & "</td>");
writeOutput("<td>$" & numberFormat(paymentResult.amount, "999.99") & " " & paymentResult.currency & "</td>");
writeOutput("<td>" & paymentResult.status & "</td>");
writeOutput("<td style='color: " & successColor & ";'><strong>" & (paymentResult.success ? "✅ YES" : "❌ NO") & "</strong></td>");
writeOutput("<td><small>" & errorText & "</small></td>");
writeOutput("</tr>");
}
writeOutput("</table>");
</cfscript>
User profile management- Configuration settings
A Software-as-a-Service (SaaS) platform serving 50,000+ users provides extensive customization options for dashboard themes, notification preferences, widget configurations, and account settings. Users progressively configure preferences over time, creating profiles with varying levels of completeness that the system must handle gracefully.
How it helps:
- Intelligent default values for unconfigured preferences
- System adapts as users configure additional settings
- Safe preference access eliminates crashes from missing configurations
- Analytics on preference usage guide product development
<cfscript>
writeOutput("<h2>👤 USE CASE 2: User Profile Management - Configuration Settings</h2>");
writeOutput("<h3>Business Context:</h3>");
writeOutput("<p>A SaaS application allows users to customize their dashboard, notification preferences, and account settings. Not all users configure every option, so the application must handle missing preferences gracefully with intelligent defaults.</p>");
// Sample user profile data with varying levels of completeness
userProfiles = [
{
userId: 1001,
name: "John Smith",
email: "john@company.com",
preferences: {
theme: "dark",
notifications: {
email: true,
sms: false,
push: true
},
dashboard: {
layout: "grid",
widgets: ["sales", "analytics", "tasks"]
},
timezone: "America/New_York"
}
},
{
userId: 1002,
name: "Sarah Johnson",
email: "sarah@startup.io",
preferences: {
theme: "light",
notifications: {
email: true
}
}
},
{
userId: 1003,
name: "Mike Chen",
email: "mike@techcorp.com"
// No preferences configured yet
}
];
writeOutput("<h4>🔧 User Preferences Processing Function:</h4>");
function processUserPreferences(userProfile) {
// Default preferences structure
defaults = {
theme: "light",
notifications: {
email: true,
sms: false,
push: false
},
dashboard: {
layout: "list",
widgets: ["overview"]
},
timezone: "UTC",
language: "en"
};
processed = {
userId: userProfile.userId,
name: userProfile.name,
email: userProfile.email,
config: {},
customizations: [],
missingSettings: []
};
// Check if user has any preferences configured
if (StructKeyExists(userProfile, "preferences")) {
userPrefs = userProfile.preferences;
// Theme preference
if (StructKeyExists(userPrefs, "theme")) {
processed.config.theme = userPrefs.theme;
arrayAppend(processed.customizations, "Theme: " & userPrefs.theme);
} else {
processed.config.theme = defaults.theme;
arrayAppend(processed.missingSettings, "Theme (using default: " & defaults.theme & ")");
}
// Notification preferences
processed.config.notifications = {};
if (StructKeyExists(userPrefs, "notifications")) {
userNotifs = userPrefs.notifications;
if (StructKeyExists(userNotifs, "email")) {
processed.config.notifications.email = userNotifs.email;
} else {
processed.config.notifications.email = defaults.notifications.email;
arrayAppend(processed.missingSettings, "Email notifications");
}
if (StructKeyExists(userNotifs, "sms")) {
processed.config.notifications.sms = userNotifs.sms;
} else {
processed.config.notifications.sms = defaults.notifications.sms;
arrayAppend(processed.missingSettings, "SMS notifications");
}
if (StructKeyExists(userNotifs, "push")) {
processed.config.notifications.push = userNotifs.push;
} else {
processed.config.notifications.push = defaults.notifications.push;
arrayAppend(processed.missingSettings, "Push notifications");
}
} else {
processed.config.notifications = defaults.notifications;
arrayAppend(processed.missingSettings, "All notification preferences");
}
// Dashboard preferences
processed.config.dashboard = {};
if (StructKeyExists(userPrefs, "dashboard")) {
userDashboard = userPrefs.dashboard;
if (StructKeyExists(userDashboard, "layout")) {
processed.config.dashboard.layout = userDashboard.layout;
arrayAppend(processed.customizations, "Dashboard layout: " & userDashboard.layout);
} else {
processed.config.dashboard.layout = defaults.dashboard.layout;
}
if (StructKeyExists(userDashboard, "widgets")) {
processed.config.dashboard.widgets = userDashboard.widgets;
arrayAppend(processed.customizations, arrayLen(userDashboard.widgets) & " custom widgets");
} else {
processed.config.dashboard.widgets = defaults.dashboard.widgets;
}
} else {
processed.config.dashboard = defaults.dashboard;
arrayAppend(processed.missingSettings, "Dashboard configuration");
}
// Timezone preference
if (StructKeyExists(userPrefs, "timezone")) {
processed.config.timezone = userPrefs.timezone;
arrayAppend(processed.customizations, "Timezone: " & userPrefs.timezone);
} else {
processed.config.timezone = defaults.timezone;
arrayAppend(processed.missingSettings, "Timezone");
}
} else {
// No preferences at all - use all defaults
processed.config = defaults;
arrayAppend(processed.missingSettings, "All preferences (new user)");
}
return processed;
}
// Process all user profiles
writeOutput("<h4>👥 User Profile Processing Results:</h4>");
for (profile in userProfiles) {
userConfig = processUserPreferences(profile);
//writeOutput("<div style='border: 1px solid #ddd; margin: 15px 0; padding: 15px; background-color: #f9f9f9;'>");
writeOutput("<h5>User: " & userConfig.name & " (ID: " & userConfig.userId & ")</h5>");
writeOutput("<table border='1' cellpadding='5' style='width: 100%;'>");
writeOutput("<tr><th>Setting</th><th>Value</th><th>Status</th></tr>");
writeOutput("<tr><td><strong>Theme</strong></td><td>" & userConfig.config.theme & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.customizations, "Theme: " & userConfig.config.theme) > 0 ? "✅ Customized" : "⚙️ Default") & "</td></tr>");
writeOutput("<tr><td><strong>Email Notifications</strong></td><td>" & (userConfig.config.notifications.email ? "Enabled" : "Disabled") & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.missingSettings, "Email notifications") > 0 ? "⚙️ Default" : "✅ Configured") & "</td></tr>");
writeOutput("<tr><td><strong>Dashboard Layout</strong></td><td>" & userConfig.config.dashboard.layout & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.missingSettings, "Dashboard configuration") > 0 ? "⚙️ Default" : "✅ Customized") & "</td></tr>");
writeOutput("<tr><td><strong>Timezone</strong></td><td>" & userConfig.config.timezone & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.customizations, "Timezone: " & userConfig.config.timezone) > 0 ? "✅ Customized" : "⚙️ Default") & "</td></tr>");
writeOutput("</table>");
if (arrayLen(userConfig.customizations) > 0) {
writeOutput("<p><strong>Custom Settings:</strong> " & arrayToList(userConfig.customizations, ", ") & "</p>");
}
if (arrayLen(userConfig.missingSettings) > 0) {
writeOutput("<p><strong>Using Defaults:</strong> <em>" & arrayToList(userConfig.missingSettings, ", ") & "</em></p>");
}
writeOutput("</div>");
}
</cfscript>
Form data validation- Customer registration
A B2B platform manages customer registration through multi-step forms with required fields for basic account creation and optional fields for enhanced profile completion. Registration forms are submitted through various channels including web forms, mobile apps, trade show kiosks, and API integrations, each with different levels of data completeness.
How it helps:
- Handles incomplete submissions while maintaining data quality standards
- Enables users to complete profiles over multiple sessions
- Accommodates varying data completeness across submission methods
- Provides visibility into profile completeness for sales prioritization
<cfscript>
writeOutput("<h2>📋 USE CASE 3: Form Data Validation - Customer Registration</h2>");
writeOutput("<h3>Business Context:</h3>");
writeOutput("<p>A customer registration system processes forms with required and optional fields. The validation system must handle incomplete submissions gracefully while ensuring required data is present for account creation.</p>");
// Sample form submissions with varying completeness
formSubmissions = [
{
submissionId: "FORM-001",
firstName: "Alice",
lastName: "Johnson",
email: "alice@example.com",
phone: "555-0123",
company: "Tech Solutions Inc",
jobTitle: "Software Engineer",
address: {
street: "123 Main St",
city: "Boston",
state: "MA",
zipCode: "02101"
},
preferences: {
newsletter: true,
productUpdates: false
}
},
{
submissionId: "FORM-002",
firstName: "Bob",
lastName: "Smith",
email: "bob@company.com",
phone: "555-0456"
// Missing optional fields
},
{
submissionId: "FORM-003",
firstName: "Carol",
email: "carol@startup.io"
// Missing last name and phone
}
];
writeOutput("<h4>🔧 Form Validation Function:</h4>");
function validateRegistrationForm(formData) {
validation = {
isValid: false,
requiredFields: ["firstName", "lastName", "email"],
optionalFields: ["phone", "company", "jobTitle", "address", "preferences"],
errors: [],
warnings: [],
processedData: {},
completeness: 0
};
completedFields = 0;
totalFields = arrayLen(validation.requiredFields) + arrayLen(validation.optionalFields);
// Validate required fields
for (field in validation.requiredFields) {
if (StructKeyExists(formData, field) && len(trim(formData[field])) > 0) {
validation.processedData[field] = trim(formData[field]);
completedFields++;
} else {
arrayAppend(validation.errors, "Required field missing: " & field);
}
}
// Process optional fields
for (field in validation.optionalFields) {
if (StructKeyExists(formData, field)) {
if (field == "address" && isStruct(formData[field])) {
// Validate address structure
addressComplete = true;
addressFields = ["street", "city", "state", "zipCode"];
processedAddress = {};
for (addrField in addressFields) {
if (StructKeyExists(formData.address, addrField) && len(trim(formData.address[addrField])) > 0) {
processedAddress[addrField] = trim(formData.address[addrField]);
} else {
addressComplete = false;
}
}
if (addressComplete) {
validation.processedData.address = processedAddress;
completedFields++;
} else {
arrayAppend(validation.warnings, "Incomplete address information");
}
} else if (field == "preferences" && isStruct(formData[field])) {
validation.processedData.preferences = formData[field];
completedFields++;
} else if (len(trim(formData[field])) > 0) {
validation.processedData[field] = trim(formData[field]);
completedFields++;
}
} else {
arrayAppend(validation.warnings, "Optional field not provided: " & field);
}
}
// Email validation
if (StructKeyExists(validation.processedData, "email")) {
if (!isValid("email", validation.processedData.email)) {
arrayAppend(validation.errors, "Invalid email format");
}
}
// Phone validation
if (StructKeyExists(validation.processedData, "phone")) {
phoneClean = reReplace(validation.processedData.phone, "[^0-9]", "", "all");
if (len(phoneClean) < 10) {
arrayAppend(validation.warnings, "Phone number may be incomplete");
}
}
// Overall validation result
validation.isValid = arrayLen(validation.errors) == 0;
validation.completeness = round((completedFields / totalFields) * 100);
return validation;
}
// Process form submissions
writeOutput("<h4>📊 Form Validation Results:</h4>");
for (submission in formSubmissions) {
validationResult = validateRegistrationForm(submission);
//writeOutput("<div style='border: 1px solid #ddd; margin: 15px 0; padding: 15px;'>");
writeOutput("<h5>Form Submission: " & submission.submissionId & "</h5>");
statusColor = validationResult.isValid ? "green" : "red";
completenessColor = validationResult.completeness >= 80 ? "green" : (validationResult.completeness >= 60 ? "orange" : "red");
writeOutput("<p><strong>Validation Status:</strong> <span style='color: " & statusColor & ";'>" & (validationResult.isValid ? "✅ VALID" : "❌ INVALID") & "</span></p>");
writeOutput("<p><strong>Form Completeness:</strong> <span style='color: " & completenessColor & ";'>" & validationResult.completeness & "%</span></p>");
if (arrayLen(validationResult.errors) > 0) {
writeOutput("<p><strong style='color: red;'>Errors:</strong></p>");
writeOutput("<ul>");
for (error in validationResult.errors) {
writeOutput("<li style='color: red;'>" & error & "</li>");
}
writeOutput("</ul>");
}
if (arrayLen(validationResult.warnings) > 0) {
writeOutput("<p><strong style='color: orange;'>Warnings:</strong></p>");
writeOutput("<ul>");
for (warning in validationResult.warnings) {
writeOutput("<li style='color: orange;'>" & warning & "</li>");
}
writeOutput("</ul>");
}
writeOutput("<p><strong>Processed Fields:</strong></p>");
writeOutput("<table border='1' cellpadding='5'>");
writeOutput("<tr><th>Field</th><th>Value</th><th>Type</th></tr>");
for (field in validationResult.processedData) {
value = validationResult.processedData[field];
fieldType = arrayFind(validationResult.requiredFields, field) > 0 ? "Required" : "Optional";
if (isStruct(value)) {
displayValue = "Structure with " & structCount(value) & " properties";
} else {
displayValue = len(value) > 30 ? left(value, 30) & "..." : value;
}
writeOutput("<tr>");
writeOutput("<td><strong>" & field & "</strong></td>");
writeOutput("<td>" & displayValue & "</td>");
writeOutput("<td>" & fieldType & "</td>");
writeOutput("</tr>");
}
writeOutput("</table>");
writeOutput("</div>");
}
</cfscript>
