Skip to content

Instantly share code, notes, and snippets.

@amirhp-com
Forked from rijkvanzanten/validate-hex-color.js
Created September 12, 2020 12:47
Show Gist options
  • Save amirhp-com/bbba62d1bf4df0e69cc0d50125da52d7 to your computer and use it in GitHub Desktop.
Save amirhp-com/bbba62d1bf4df0e69cc0d50125da52d7 to your computer and use it in GitHub Desktop.
/**
* Validates hex value
* @param {String} color hex color value
* @return {Boolean}
*/
function isValidHex(color) {
if(!color || typeof color !== 'string') return false;
// Validate hex values
if(color.substring(0, 1) === '#') color = color.substring(1);
switch(color.length) {
case 3: return /^[0-9A-F]{3}$/i.test(color);
case 6: return /^[0-9A-F]{6}$/i.test(color);
case 8: return /^[0-9A-F]{8}$/i.test(color);
default: return false;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment