javascriptcss-selectors

Check if CSS selector is valid


I have a field for users to input a CSS selector and I want to check if it's valid (according to css3 specification). I tried to use expressions from css3 specification as suggested in another stackoverflow topic, but it didn't work - the regexp I built just didn't match valid selectors. What I have for now is simply:

try {
     document.querySelector(selector);
} catch (e) {
     // handle bad input
}

But it doesn't seem like a good solution - querySelector function is designed for getting elements, and checking of selector is just a side effect. Furthermore it doesn't provide any information about what is wrong with the selector.

What I'm looking for is something like document.validateSelector or library for parsing CSS selectors.


Solution

  • You can use a library to verify if the selector is valid, and probably get more details from parsing. Check the css selector parser.