Notes

JavaScript - Regular Expression to validate RGB/HSL CSS colors

author: Paul Kim

categories: js, regex

tags: js, regex

Regular Expression to validate RGB/HSL CSS colors

the regular expression to validate RGB/RGBA/HSL/HSLA CSS colors are:

RegExp(
  `^(hsl|rgb)a?\\(\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*,\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*,\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*\\)$`
)

regular expression to match rgb, rgba, hsl, hsla:

RegExp(`^rgba?$`).test(`rgb`) // true
RegExp(`^rgba?$`).test(`rgba`) // true
RegExp(`^hsla?$`).test(`hsl`) // true
RegExp(`^hsla?$`).test(`hsla`) // true

regular expression to match 0-255 or 000-255:

// regex to match 0 - 255 (0, 1, 2, 3, 4, ...  254, 255)
([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])

// regex to match 0 - 255 (but also matches two-digits w/ leading 0s - 01, 02, 03, 04, 05, 06, 07, 08, 09)
(1?\\d{2}|2[0-4]\\d|25[0-5])

regular expression to match valid RGB/HSL CSS colors:

RegExp(
  `^(hsl|rgb)a?\\(\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`
).test(`rgba(255`)

RegExp(
  `^(hsl|rgb)a?\\(\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*,\\s*$`
).test(`rgba(  255  ,  `)

RegExp(`^(hsl|rgb)a?\\(\\s*
([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*
,\\s*
([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*
,\\s*
([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*
\\)
$`).test(`rgba(  255  ,  255  ,  255  )`)

// this is it!
RegExp(
  `^(hsl|rgb)a?\\(\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*,\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*,\\s*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\s*\\)$`
).test(`rgba(  255  ,  255  ,  255  )`)

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.