DEV Community

SumantaWeb
SumantaWeb

Posted on

Challenge #1

Okay,

IT'SS THE LAST MONTH OF THE YEAR!!!

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

Challenges!
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.

Discussion (4)

Collapse
jonrandy profile image
Jon Randy • Edited on

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
Collapse
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

Collapse
jonrandy profile image
Jon Randy • Edited on

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

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