Search code examples
javascriptjquerysizzle

Is there a way to validate a Sizzle selector?


Is there a way to validate (verify that its constructed correctly) a Sizzle selector without running it?


Solution

  • Well, as Russ says, since Sizzle interprets the selector, it cannot validate it without evaluating it.

    However, you can catch the exception thrown by Sizzle to determine if a selector is valid or not:

    function isSelectorValid(selector)
    {
        try {
            $(selector);
        } catch (x) {
            return false;
        }
        return true;
    }
    

    Your can test this solution here.


    EDIT: For the sake of history, my original (and overengineered) answer was:

    However, it's possible to temporarily override Sizzle's error management in order to extract a boolean value from the error status of its last parse operation. The following solution takes advantage of the fact that jQuery exposes Sizzle through $.find (so far):

    function isSelectorValid(selector)
    {
        var oldErrorMethod = $.find.error;
        try {
            $.find.error = function(msg) {
                valid = false;
                oldErrorMethod(msg);
            };
            $(selector);
            return true;
        } catch (x) {
            return false;
        } finally {
            $.find.error = oldErrorMethod;
        }
    }
    

    That can arguably be considered as a horrible hack, but it works: you can test it here.