Reputation: 2121
I want to parse the input and check whether the entered colored format is in either RGBA or HEX format and also give user space for entering color names of regular colors with a switch case.
I found a regex for hex colors and regular color names but was unable to find one for RGBA.
Javascript
function verifycolor(colorcode) {
var regColorcode = /^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/;
if(regColorcode.test(colorcode) == false)
document.getElementById("status").innerHTML = "Color is not yet valid.";
else if(regColorcode.test(colorcode) == true)
document.getElementById("status").innerHTML = "You have entered a valid color code";
}
jsfiddle didn't work for me with this code. Dunno the reason. So it's here.
Can anyone help me out to do the same for RGBA colors. It would be great if the regex can parse it into red, green, blue and alpha.
Upvotes: 2
Views: 2109
Reputation: 6203
rgba\(((25[0-5])|(2[0-4]\d)|(1?\d\d)|\d)%?, *((25[0-5])|(2[0-4]\d)|(1?\d\d)|\d)%?, *((25[0-5])|(2[0-4]\d)|(1?\d\d)|\d)%?, *((25[0-5])|(2[0-4]\d)|(1?\d\d)|\d)%?\)
This matches rgb() with, inside, 4 numbers between 0 and 255, separated by ,
(or ,<space>
) followed possibly by a %
sign. Of course percentages should be no more than 100%, but for the purpose it'll do.
Upvotes: 0
Reputation: 145398
Some search gave me this RGB color parser:
It does exactly what you want (even can output the color channels). And of course it can be used for color verification.
From the description:
A JavaScript class that accepts a string and tries to figure out a valid color out of it. Some accepted inputs are for example:
rgb(0, 23, 255)
#336699
ffee66
fb0
red
darkblue
cadet blue
DEMO: http://www.phpied.com/files/rgbcolor/rgbcolor.html
Upvotes: 3