我使用正则表达式来表示十六进制。
/^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
但我不知道我应该做什么来找到 rgb、rgba 和 hsl。我正在以字符串形式获取输入。例如,输入将包含“rgb(0,0,0)”或“rgb(0,0,0,0.2)”。
这里有不同的选项:
使用浏览器的验证。创建一个 dummy HTML 元素,指定颜色并检查是否已设置。这是迄今为止最好的选择。它不仅更容易,而且还可以向前兼容。
function CheckValidColor(color) {
var e = document.getElementById('divValidColor');
if (!e) {
e = document.createElement('div');
e.id = 'divValidColor';
}
e.style.borderColor = '';
e.style.borderColor = color;
var tmpcolor = e.style.borderColor;
if (tmpcolor.length == 0) {
return false;
}
return true;
}
// function call
var inputOK = CheckValidColor('rgb( 0, 0, 255)');
对于浏览器接受的所有颜色,这都会返回
true
,即使在您可能认为无效的情况下也是如此。
如果您捕获任何看起来像数字的内容,您将能够使用
IF clauses
单独验证每个参数。这将使您能够向用户提供更好的反馈。
a) #hex:
^(#)((?:[A-Fa-f0-9]{3}){1,2})$
还捕获哈希值以与以下表达式保持一致。 演示
b) rgb()、rgba()、hsl() 和 hsla():
^(rgb|hsl)(a?)[(]\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*(?:,\s*([\d.]+)\s*)?[)]$
这将为函数和每个参数创建捕获。 演示
不推荐这个选项,主要是因为它很难阅读,它不能保证匹配所有用例,如果你尝试调试它,它会让你很头疼。以下正则表达式验证允许的参数数量和范围。
a) #hex:
^#(?:[A-Fa-f0-9]{3}){1,2}$
DEMO
b) rgb():
^rgb[(](?:\s*0*(?:\d\d?(?:\.\d+)?(?:\s*%)?|\.\d+\s*%|100(?:\.0*)?\s*%|(?:1\d\d|2[0-4]\d|25[0-5])(?:\.\d+)?)\s*(?:,(?![)])|(?=[)]))){3}[)]$
演示
c) rgba():
^^rgba[(](?:\s*0*(?:\d\d?(?:\.\d+)?(?:\s*%)?|\.\d+\s*%|100(?:\.0*)?\s*%|(?:1\d\d|2[0-4]\d|25[0-5])(?:\.\d+)?)\s*,){3}\s*0*(?:\.\d+|1(?:\.0*)?)\s*[)]$
DEMO
d) hsl():
^hsl[(]\s*0*(?:[12]?\d{1,2}|3(?:[0-5]\d|60))\s*(?:\s*,\s*0*(?:\d\d?(?:\.\d+)?\s*%|\.\d+\s*%|100(?:\.0*)?\s*%)){2}\s*[)]$
演示
e) hsla():
^hsla[(]\s*0*(?:[12]?\d{1,2}|3(?:[0-5]\d|60))\s*(?:\s*,\s*0*(?:\d\d?(?:\.\d+)?\s*%|\.\d+\s*%|100(?:\.0*)?\s*%)){2}\s*,\s*0*(?:\.\d+|1(?:\.0*)?)\s*[)]$
DEMO
现在大家在一起:
通过上述表达式,我们可以创建这一行来验证所有合法的颜色值:
^(?:#(?:[A-Fa-f0-9]{3}){1,2}|(?:rgb[(](?:\s*0*(?:\d\d?(?:\.\d+)?(?:\s*%)?|\.\d+\s*%|100(?:\.0*)?\s*%|(?:1\d\d|2[0-4]\d|25[0-5])(?:\.\d+)?)\s*(?:,(?![)])|(?=[)]))){3}|hsl[(]\s*0*(?:[12]?\d{1,2}|3(?:[0-5]\d|60))\s*(?:\s*,\s*0*(?:\d\d?(?:\.\d+)?\s*%|\.\d+\s*%|100(?:\.0*)?\s*%)){2}\s*|(?:rgba[(](?:\s*0*(?:\d\d?(?:\.\d+)?(?:\s*%)?|\.\d+\s*%|100(?:\.0*)?\s*%|(?:1\d\d|2[0-4]\d|25[0-5])(?:\.\d+)?)\s*,){3}|hsla[(]\s*0*(?:[12]?\d{1,2}|3(?:[0-5]\d|60))\s*(?:\s*,\s*0*(?:\d\d?(?:\.\d+)?\s*%|\.\d+\s*%|100(?:\.0*)?\s*%)){2}\s*,)\s*0*(?:\.\d+|1(?:\.0*)?)\s*)[)])$
或者正则表达式爱好者可以检查这个巨大的正则表达式,有 148 个颜色名称。但我绝不会建议使用这种模式。请使用第一个选项,创建一个虚拟元素,这是覆盖浏览器所有用例的唯一方法。
我不知道其他浏览器,但在 Chrome 中,只有在有效时才会设置颜色:
var isValidColor = function(color) {
var el = document.createElement('div');
el.style.backgroundColor = color;
return el.style.backgroundColor ? true : false;
};
console.log(isValidColor('#ff0000')); // true
console.log(isValidColor('rgb(0, 0)')); // false
不过它也会有陷阱,因为 Chrome 会自动对数字进行舍入:
// 0, 0, 256 is not a valid color, but this says yes
console.log(isValidColor('rgb(0, 0, 256)')); // true
验证十六进制、RGB 和 HSL 格式颜色的函数:
function isValidColor(colorString) {
const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
const rgbRegex = /^rgb(a)?\(\s*((25[0-5]|2[0-4]\d|1\d{2}|\d{1,2})\s*,\s*){2}(25[0-5]|2[0-4]\d|1\d{2}|\d{1,2})\s*(,\s*\d+(\.\d+)?)?\)$/i;
const hslRegex = /^hsla?\(\s*((360|3[0-5]\d|[12]\d{2}|[1-9]\d|\d)\s*,\s*){2}(360|3[0-5]\d|[12]\d{2}|[1-9]\d|\d)\s*(,\s*\d+(\.\d+)?)?\)$/i;
if (hexRegex.test(colorString)) {
return true; // Valid hex color
} else if (rgbRegex.test(colorString)) {
const values = colorString.match(/\d+(\.\d+)?/g); // Extract numeric values
const isValid = values.every(value => value >= 0 && value <= 255); // Check if values are within range
return isValid && (values.length === 3 || values.length === 4); // Valid RGB or RGBA color
} else if (hslRegex.test(colorString)) {
const values = colorString.match(/\d+(\.\d+)?/g); // Extract numeric values
const isValid = values.every(value => value >= 0 && value <= 100); // Check if values are within range
return isValid && (values.length === 3 || values.length === 4); // Valid HSL or HSLA color
}
return false; // Invalid color format
}
// Sample usage:
console.log(isValidColor('#ff0000')); // true
console.log(isValidColor('rgb(255, 0, 0)')); // true
console.log(isValidColor('rgba(0, 0, 0, 0.5)')); // true
console.log(isValidColor('hsl(120, 100%, 50%)')); // true
console.log(isValidColor('invalidcolor')); // false