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") ?? "[]");
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).
const colors = ['#ab432f', '#4ADEf9', '#gwhi32', '#2fad8923', 'foo']
const colorsSanitized = colors.filter(color => color.match(/^#[\dabcdef]{6}$/i))
console.log(colorsSanitized)
This regex matches a case-insensitive string that
^# // starts with a #
[ ] // matches a single character that's either
\d // any digit
abcdef // or any letter A through F
{6} // exactly 6 times
$ // at which point the string ends