Skip to content

Commit

Permalink
fix(is-valid-rgba): pass more valid and less invalid values + test (#31)
Browse files Browse the repository at this point in the history
* test: add isValidRGBA test

* fix(is-valid-rgba): pass more valid and less invalid values

- Opacity 1 was invalid.
- R, G or B 256-999 were valid.
  • Loading branch information
Thomaash authored Aug 2, 2019
1 parent 92dc6ef commit 047b0e7
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ export { uuid4 as randomUUID } from 'vis-uuid'
// code from http://momentjs.com/
const ASPDateRegex = /^\/?Date\((-?\d+)/i

// Hex color
// Color REs
const fullHexRE = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
const shortHexRE = /^#?([a-f\d])([a-f\d])([a-f\d])$/i
const rgbaRE = /^rgba\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *([01]|0?\.\d+) *\)$/i

/**
* Hue, Saturation, Value.
Expand Down Expand Up @@ -1442,9 +1443,7 @@ export function isValidRGB(rgb: string): boolean {
* @returns True if the string is valid, false otherwise.
*/
export function isValidRGBA(rgba: string): boolean {
rgba = rgba.replace(' ', '')
const isOk = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(0?.{1,3})\)/i.test(rgba)
return isOk
return rgbaRE.test(rgba)
}

/**
Expand Down
66 changes: 66 additions & 0 deletions test/is-valid-rgba.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { expect } from 'chai'

import { isValidRGBA } from '../src'

describe('isValidRGBA', function(): void {
const valid = [
'RGBA(7, 200, 8, .7)',
'RGBA(7, 200, 8, 0.7)',
'RGba(255,255,255,1)',
'Rgba(0,12,123,0.321)',
'rGBa(44, 7, 220,0.92)',
'rGba(210, 50,220, 0.42)',
'rgBa(210,50, 220,0.37)',
'rgbA( 72 , 11 , 123 , 0.21 )',
'rgba(0,0,0,0)',
]
const invalid = [
' ',
' RGBA(0, 12, 123, 0.3) ',
' RGBA(210,50,220,0)',
'#000000',
'#abc',
'',
'(0,12,123)',
'0',
'0,12,123)',
'5,7,9',
'RGBA(210, 50, 220, 0.77) ',
'false',
'garbage',
'hi rgb(0,12,123)',
'orange',
'rgb 7, 7, 7',
'rgb(0, 12, 123)',
'rgb(0,12,123, 0.2)',
'rgba(0, 0, -1, 0)',
'rgba(0, 0, 0, -1)',
'rgba(0, 0, 0, 1.1)',
'rgba(0, 0, 0, 2)',
'rgba(0, 12, 123, 0.7) :-)',
'rgba(0, 300, 0, 0)',
'rgba(0,1 2,0,0)',
'rgba(0,12,123,0.3',
'rgba(256, 0, 0, 0)',
'rgba(7, 8, 9)',
'rgba(7,8,9)',
'the color is #00AAAA',
'true',
]

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

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

0 comments on commit 047b0e7

Please sign in to comment.