So..., the answer is that none of your JS code is ever firing, because Chrome is implementing HTML5 input elements, including form validation. So, unless you correctly fill in the fields, your validation code will never fire!
In HTML5 the required
attribute is a boolean, its either true or false. According to the spec, the browser should fire an invalid
event on the problem field. You can cancel the default blocking behavior at that point if you want. However, your script breaks down again where you try attr('required')
. It will return true
or false
in Chrome, using HTML5, not a value like email
as you expect.
So you need to add these two pieces if you want this to work:
$(":input").bind("invalid", function(e){
e.preventDefault(); // Don't block the form submit
});
And then re-factor your code from
var a = $(this).attr('required');
to be
var a = $(this).attr('required') ? $(this).attr('type') : "";
And change your switch statement to match if needed
One last idea: You could also take a really cool approach (aka Feature Detection), and do this instead:
Wrap the inside of your current validate:
function with this:
if(typeof $('<input />')[0].checkValidity === "undefined") {
... existing code ..
} else {
$(':input').bind('invalid', function(){
$(this).addClass('error');
}).blur(function(){
// If valid, turn off error
// If invalid, turn on error
$(this).toggleClass('error', !this.checkValidity());
});
}
Here is a demo of the second version that will work in Chrome and possibly a current/beta version of Opera.