Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active March 7, 2025 17:09
Show Gist options
  • Save JamoCA/c4079d7c813b0ad3d1a28cfc7551c355 to your computer and use it in GitHub Desktop.
Save JamoCA/c4079d7c813b0ad3d1a28cfc7551c355 to your computer and use it in GitHub Desktop.
isValidHexString - ColdFusion / CFML UDF to validates if a string is a valid hexadecimal value.
/**
* isValidHexString UDF
* Validates if a string is a valid hexadecimal value
* @displayname isValidHexString
* @author James Moberg http://sunstarmedia.com, @sunstarmedia
* @version 1
* @lastUpdate 3/7/2025
* @gist https://gist.github.com/JamoCA/c4079d7c813b0ad3d1a28cfc7551c355
* @blog https://dev.to/gamesover/isvalidhexstring-coldfusion-udf-1cge
* @twitter https://x.com/gamesover/status/1898058042618658843
* @LinkedIn https://www.linkedin.com/posts/jamesmoberg_coldfusion-cfml-activity-7303824050869489666-YZxL
* @param hexString The string to validate
* @param length Optional specific length to enforce (e.g., 6 for color codes)
* @return Boolean indicating if the string is a valid hex value
*/
boolean function isValidHexString(required string hexString, numeric length) {
// Remove any leading "0x" or "#" if present (common in hex notation)
local.cleanedString = tostring(arguments.hexString).replaceAll("^(0x|##)", "");
// Check if string matches hex pattern
local.isValid = refindnocase("^[0-9A-F]+$", local.cleanedString) gt 0;
// If a specific length is provided, enforce it
if (structkeyexists(arguments, "length") && arguments.length gt 0) {
local.isValid = local.isValid && (len(local.cleanedString) eq arguments.length);
}
// Ensure the string isn't empty after cleaning
return local.isValid && len(trim(local.cleanedString)) gt 0;
}
tests = [
["hexString": "1A2B3C", "msg": "Returns true"],
["hexString": "1a2b3C", "msg": "Returns true (case is not relevant)"],
["hexString": "1G2B3C", "msg": "Returns false (G is not valid)"],
["hexString": "##FF0000", "msg": "Returns true (ignores ##)"],
["hexString": "0xDEADBEEF", "msg": "Returns true (ignores 0x)"],
["hexString": "ABCDEF", "length":6, "msg": "Returns true (exact length 6)"],
["hexString": "ABCD", "length":6, "msg": "Returns false (wrong length)"],
["hexString": "", "msg": "Returns false (empty)"]
];
writeoutput("<h2>isValidHexString(required string hexString, numeric length)</h2>");
for (test in tests){
hLen = test.keyexists("length") ? ", #test.length#" : "";
writeoutput('<div>("#test.hexString#"#hLen#): <b>#isValidHexString(argumentcollection=test)#</b> - <i>#test.msg#</i></div>');
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment