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)
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
: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"))
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With