DEV Community


Posted on

Challenge #1



So all the business of the whole year comes to an end in few days. But one work left...

My web dev teacher gave us a challenge to complete.. And I am sure gonna complete it by today.. let's see if I can.

The challenge :-

"Build a web page with an input field. If you type a valid css color code in the field, the background of the page should change to that color. If the color code is illegal, it should show an error message."

Note : DO NOT use input type=color.

So let's see if I can. You all also try and say in the comments if you could complete it.

I would send the code in another post someday..

Till then byee.

Top comments (4)

jonrandy profile image
Jon Randy 🎖️ • Edited

This should be useful:

const isValidCSSColour = str => {
  const s = new Option().style
  s.color = str
  return s.color != ''

isValidCSSColour('red') // true
isValidCSSColour('kumquat') // false
isValidCSSColour('#fc0') // true
isValidCSSColour('#123456') // true
isValidCSSColour('#fff8') // true
isValidCSSColour('#fg3') // false
isValidCSSColour('#ffffff33') // true
isValidCSSColour('var(--myVar)') // true
isValidCSSColour('rgb(10,30,20)') // true
isValidCSSColour('rgb(10,error,20)') // false
isValidCSSColour('hsl(0,100%, calc((1 - var(--enable))*100%)') // true
Enter fullscreen mode Exit fullscreen mode
saifullahusmani profile image
Saifullah Usmani

Check if the input starts with #, rgb or rgba.
In rgb check if 2 commas and in rgba check if 3 commas
Check if integers check if within 255 check in rgba if last number is greater or less than 0 and 1

jonrandy profile image
Jon Randy 🎖️ • Edited

Unfortunately, that doesn't even come close to checking all valid CSS colours - there are many, many, named colours that are completely valid (red, white, green, burlywood, chartreuse, etc.) as well as CSS variables like var(--myColour).

Also, checking if it starts with # really is not enough in the case of hex values.

There's actually a very quick, short way of checking ALL of this... but I won't give it away here just yet

saifullahusmani profile image
Saifullah Usmani

I thought it is a quick thing. I know it is not 100% correct method. But now I got your point.