4

Is there a way to programmatically check the validity of a javascript/jquery selector?

like .class is ok but .class, is not

programmatically in javascript or any backend language (besides going through jQuery source code)

so in pseudo code

 def selectorErrors(selector)

     // do nasty stuff to the selector
     if valid?
      return nil
    else
      return errors
    end
end
10
  • 2
    @Juhana No it is not Commented Jul 26, 2015 at 14:00
  • @Juhana It looks like it is: jsfiddle.net/w3gqd78e Commented Jul 26, 2015 at 14:01
  • exactly my point. Is there a way to programmatically solve this arguement? Commented Jul 26, 2015 at 14:01
  • 1
    @RoyShmuli is there such a regex? Commented Jul 26, 2015 at 14:04
  • 2
    how about a try/catch on document.querySelector(str) - less overhead than jQuery, although there are some jQuery specific "selectors" that querySelector wont allow Commented Jul 26, 2015 at 14:05

3 Answers 3

7

This should validate 99% of what you can throw at jQuery with far less overhead

function validateQuery(str) {
    try {
        document.querySelector(str);
        return true;
    }
    catch(e) {
        // something here to check WHY it's invalid
    }
    return false;
}

edit: ok, this wont tell you WHAT is wrong with it, but it does (quickly) check the validity - at least you'll only need to check WHY it's invalid, not IF :p

Sign up to request clarification or add additional context in comments.

4 Comments

Instead of document.querySelector(str); shouldn't it just be: jQuery(str);? Because ya, jQuery has some pseudo selectors (':has(), ':eq()', etc...) not supported by document.querySelector() method
In fact, question isn't clear about it: Validation of a javascript/css selector & javascript/jquery selector
Here’s a fiddle based on your method to test selectors for validity.
-2
existOrValid('#a')

function existOrValid(a){

    if (/^[#,.]{0,1}[A-Za-z][0-9A-Za-z\-\._:]*$/.test(a)) {
    alert('valid');
}

}

Works on simple class ,id selectors but needs modification for nested queries

Comments

-5

$('.a.b')

If you want an intersection, just write the selectors together without spaces in between. So for an element that has an ID of a with classes b and c, you would write:

$('#a.b.c')

1 Comment

this doesn't check for validation, as in given a selector tell me if its good or not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.