Skip to content

Commit

Permalink
fix: prevent isValidRGB from passing invalid RGB strings (#28)
Browse files Browse the repository at this point in the history
* test: add isValidRGB test

* fix: prevent isValidRGB from passing invalid RGB strings
  • Loading branch information
Thomaash committed Aug 1, 2019
1 parent bc25740 commit ef52283
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/util.ts
Expand Up @@ -1426,9 +1426,7 @@ export function isValidHex(hex: string): boolean {
* @returns True if the string is valid, false otherwise.
*/
export function isValidRGB(rgb: string): boolean {
rgb = rgb.replace(' ', '')
const isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb)
return isOk
return /^ *rgb\( *\d{1,3} *, *\d{1,3} *, *\d{1,3} *\) *$/i.test(rgb)
}

/**
Expand Down
55 changes: 55 additions & 0 deletions test/is-valid-rgb.test.ts
@@ -0,0 +1,55 @@
import { expect } from 'chai'

import { isValidRGB } from '../src'

describe('isValidRGB', function(): void {
const valid = [
' Rgb(0,12,123) ',
' rGb(210, 50,220)',
'RGB(7, 200, 8)',
'RGb(255,255,255)',
'Rgb(0,12,123)',
'rGB(44, 7, 220)',
'rGb(210, 50,220) ',
'rGb(210, 50,220)',
'rgB(210,50, 220)',
'rgb( 72 , 11 , 123 )',
'rgb(0,0,0)',
]
const invalid = [
' ',
'#000000',
'#abc',
'',
'(0,12,123)',
'0',
'0,12,123)',
'5,7,9',
'false',
'garbage',
'hi rgb(0,12,123)',
'orange',
'rgb 7, 7, 7',
'rgb(0, 12, 123) :-)',
'rgb(0,12,123',
'rgba(7,8,9,0.3)',
'the color is #00AAAA',
'true',
]

describe('Valid', function(): void {
valid.forEach((color): void => {
it(color, function(): void {
expect(isValidRGB(color)).to.be.true
})
})
})

describe('Invalid', function(): void {
invalid.forEach((color): void => {
it(color, function(): void {
expect(isValidRGB(color)).to.be.false
})
})
})
})

0 comments on commit ef52283

Please sign in to comment.