skip to Main Content

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


  1. 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
    
    Login or Signup to reply.
  2. You can use a RegExp and Array.prototype.filter() to filter out the valid or invalid color codes:

    const colors = [
      // Valid:
      "#0283fb",
      "#35363a",
      "#f6383a",
      "#9129c8",
      "#38bdf8",
      "#ded8d8",
      // Invalid:
      "#325363a",
      "#f64383a",
      "9129c8",
      "#13/12sc",
      "#ded8d8c",
    ];
    
    const hexColorRegexp = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
    
    const validColors = colors.filter(color => hexColorRegexp.test(color));
    
    const invalidColors = colors.filter(color => !hexColorRegexp.test(color));
    
    console.log('VALID =', validColors);
    
    console.log('INVALID =', invalidColors)

    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).

    Login or Signup to reply.
  3. If only 6 digit hex codes are valid:
    in the filter function check if

    • code is 7 symbols long
    • starts with #
    • each symbol after # can be parsed as HEX
    const colors = ["#0183fb","#35363a","#f6383a","#9129c8","#38bdf8","#ded8d8", "#028s3fb","#325363a","#f64383a","9129c8","#13/12s"];
    
    const filtered = colors.filter(c =>
      c.length === 7 &&
      c[0] === '#' && 
      [...c.slice(1, 6)].every(d => !isNaN(parseInt(d, 16)))
    );
    
    console.log(filtered)

    But you might extend from this towards the other valid colors.

    Login or Signup to reply.
  4. Regex taken from this answer: How to identify a given string is hex color format

    Give this a whirl…

    const colorsArray = JSON.parse(localStorage.getItem("colorsArray") ?? "[]");
    
    const validateColors = (colors = []) => {
        const hexColor = new RegExp('^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$')
        const listOfColors = colors;
    
        const valid = []
        listOfColors.map((item) => {
            if (!item.match(hexColor)) return
            valid.push(item)
        })
    
        return valid
    }
    
    
    validateColors(colorsArray)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search