Back to Freecodecamp

Challenge 210: HSL Validator

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f50f.md

latest2.2 KB
Original Source

--description--

Given a string, determine whether it is a valid CSS hsl() color value.

  • A valid HSL value must be in the format "hsl(h, s%, l%)", where:

    • h (hue) must be a number between 0 and 360 (inclusive).
    • s (saturation) must be a percentage between 0% and 100%.
    • l (lightness) must be a percentage between 0% and 100%.
  • Spaces are only allowed:

    • After the opening parenthesis
    • Before and/or after the commas
    • Before and/or after closing parenthesis
  • Optionally, the value can end with a semi-colon (";").

For example, "hsl(240, 50%, 50%)" is a valid HSL value.

--hints--

isValidHSL("hsl(240, 50%, 50%)") should return true.

js
assert.isTrue(isValidHSL("hsl(240, 50%, 50%)"));

isValidHSL("hsl( 200 , 50% , 75% )") should return true.

js
assert.isTrue(isValidHSL("hsl( 200 , 50% , 75% )"));

isValidHSL("hsl(99,60%,80%);") should return true.

js
assert.isTrue(isValidHSL("hsl(99,60%,80%);"));

isValidHSL("hsl(0, 0%, 0%) ;") should return true.

js
assert.isTrue(isValidHSL("hsl(0, 0%, 0%) ;"));

isValidHSL("hsl( 10 , 20% , 30% ) ;") should return true.

js
assert.isTrue(isValidHSL("hsl(  10  ,  20%   ,  30%   )    ;"));

isValidHSL("hsl(361, 50%, 80%)") should return false.

js
assert.isFalse(isValidHSL("hsl(361, 50%, 80%)"));

isValidHSL("hsl(300, 101%, 70%)") should return false.

js
assert.isFalse(isValidHSL("hsl(300, 101%, 70%)"));

isValidHSL("hsl(200, 55%, 75)") should return false.

js
assert.isFalse(isValidHSL("hsl(200, 55%, 75)"));

isValidHSL("hsl (80, 20%, 10%)") should return false.

js
assert.isFalse(isValidHSL("hsl (80, 20%, 10%)"));

--seed--

--seed-contents--

js
function isValidHSL(hsl) {

  return hsl;
}

--solutions--

js
function isValidHSL(hsl) {
  const regex = /^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)\s*;?$/;

  const match = hsl.match(regex);
  if (!match) return false;

  const hue = Number(match[1]);
  const sat = Number(match[2]);
  const light = Number(match[3]);

  if (hue < 0 || hue > 360) return false;
  if (sat < 0 || sat > 100) return false;
  if (light < 0 || light > 100) return false;

  return true;
}