How to Check If Color String Valid
We have a project based on ReactNative. Recently, we encountered a problem, that is, when the operation colleague configured the color value, one was missing, and only five were allocated, which led to page confusion and JS errors.
In addition to increasing restrictions on the configuration platform, we have also taken some inspection measures in the project.
The problem is, how to check if the color string is valid using JS.
If our project is a Web project, we can consider non-regular solutions, such as
1 | const isColor = (strColor) => { |
You can also use CSS.supports()
, such as
1 | CSS.supports('color', '#007') |
Unfortunately, our project is a ReactNative project, and the above web solution cannot be used, so we can only start with the idea of regular
matching.
For simplicity, we agree to only support the form of #
followed by hexadecimal numbers. Like #FFF
, #00FFFF
, #FF00FFFF
. And we need to support argb
, which is 8
or 4
hexadecimal numbers.
It means that the strings in the following forms do not support configuration delivery for the time being.
- blue / red / yellow
- rgba(255, 255, 255, 0.5)
- hsla(235, 100%, 50%, .5)
- etc
Simply put, it only supports the form of #
following 3
, 4
, 6
, and 8
hexadecimal digits.
- #000
- #FFFFFF
- #FFFF
- #FFFFFFFF
During the actual development process, we also checked the information on the Internet, but actually got a lot of wrong results. The correct results should be similar to the following
1 | const isColor = (strColor) => { |
Of course, it is also correct to use i
for case fuzzy matching, or to add ?:
as a zero-width assertion.
A common mistake is as follows:
Both of the following are wrong
, because the string of 7
hexadecimal digits cannot be correctly checked. A 7-digit
hexadecimal number should not be a valid
color value string.
1 | /^#(([0-9A-Fa-f]{3,4}){2}|[0-9A-Fa-f]{3,4})$/ |
Note the order of {2}
and {3,4}
in the correct and incorrect codes.