Currently, I only check if it’s not null or undefined and I want to make sure that each hex color is correct otherwise discard the wrong hex and move to the next. If the format is completely wrong then just reset to an empty array. Any idea how I can do this type of validation?
Correct example of colors array(only 6 digit starting with # are valid):
["#0283fb","#35363a","#f6383a","#9129c8","#38bdf8","#ded8d8"]
Incorrect example of colors array(basically any non-hex color code or non-6 digit hex color):
["#028s3fb","#325363a","#f64383a","9129c8","#13/12sc","#ded8d8"]
If the localStorage string format is wrong or if the loop that checks each hex color fails then reset to [].
const colorsArray = JSON.parse(localStorage.getItem("colorsArray") ?? "[]");
4
Answers
If you have an array of hex color strings and you want to discard the ones that aren’t valid, you could
.filter()
the array using regular expressions.Here’s an example for filtering out everything except for valid 6-digit hex strings. (But note that 3- and 8-digit hex strings could also be considered valid).
This regex matches a case-insensitive string that
You can use a RegExp and
Array.prototype.filter()
to filter out the valid or invalid color codes:Keep in mind HEX colors can also use a shorthand 3-digit code (e.g.
#FF0
) and can use both lowercase and uppercase letters (a-f
+A-F
), and might even include an additional alpha channel (e.g.#FF002299
).If
only 6 digit hex codes are valid
:in the
filter
function check if#
#
can be parsed as HEXBut you might extend from this towards the other valid colors.
Regex taken from this answer: How to identify a given string is hex color format
Give this a whirl…