Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery support ":invalid" selector

I get the following console message:

[16:04:01.292] Error: Syntax error, unrecognized expression: unsupported pseudo: invalid @ http://localhost:8080/assets/js/jquery-1.9.1.min.js:4

When I try something like:

if( $(e.target).is(':invalid') ){ ... }

How do I fix this?

Here's an example: http://jsfiddle.net/L4g99/ - try changing the jQuery version (stops working after 1.9)

like image 465
jldupont Avatar asked Apr 04 '13 20:04

jldupont


3 Answers

Using querySelectorAll as suggested by @JanDvorak (and his answer should be accepted for thinking of that), you can write your own expression, making .is(':invalid') valid ?

jQuery.extend(jQuery.expr[':'], {
    invalid : function(elem, index, match){
        var invalids = document.querySelectorAll(':invalid'),
            result = false,
            len = invalids.length;

        if (len) {
            for (var i=0; i<len; i++) {
                if (elem === invalids[i]) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
});

now you can do :

if( $(e.target).is(':invalid') ){ ... }

FIDDLE

like image 107
adeneo Avatar answered Oct 04 '22 15:10

adeneo


:invalid is, indeed, not a valid jQuery selector (pseudoclass).

According to the link you posted, however, it is a valid CSS selector (not supported in IE<10).

A fiddle by Adeneo shows that, as suspected, while it doesn't work in jQuery, it can be used via the native querySelector/querySelectorAll methods. So, while this doesn't work:

if($(e.target).is(":invalid"))  //SyntaxError

This does (except in IE<10):

if(~[].indexOf.call(document.querySelectorAll(":invalid"),e.target))

This should work as well (in the future or after the neccessary shimming; see caniuse):

if(e.target.matches(":invalid"))
like image 32
John Dvorak Avatar answered Oct 04 '22 14:10

John Dvorak


You can use element's validity attribute (see MDN).

Now combining it with @adeneo's idea:

jQuery.extend(jQuery.expr[':'], {
    invalid : function(elem, index, match){
        return elem.validity !== undefined && elem.validity.valid === false;
    },

    valid : function(elem, index, match){
        return elem.validity !== undefined && elem.validity.valid === true;
    }


});
like image 3
Nikita Malyavin Avatar answered Oct 04 '22 14:10

Nikita Malyavin