Individual Input Validation on Blur
I'm trying to use HTML5 to validate a number input. I am using jQuery to create the elemen开发者_如何学Pythont. How can I have the browser display the error message onBlur without having to click the submit button?
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"});
Set up a .blur() handler. See here.
jQuery(document.createElement('input')).attr({"type":"number","min":"0","max":"60","step":"1","value":"5"}).blur(function(){
var val = parseInt(jQuery(this).val(),10);
if(val < parseInt(jQuery(this).attr('min'), 10))
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to min
if(val > parseInt(jQuery(this).attr('max'), 10)){
jQuery(this).val(parseInt(jQuery(this).attr('min'), 10)); // Set value to max
});
Something along those lines
Actually, you can't invoke the native validation ui through an API. Due to the fact, that the the validation ui automatically also focuses the element, this would not be a good usability (user can't leave field invalid and decide to do something else on the page).
If you want to do this: you have to implement the validation yourslf using the validity property and the validationMessage property. The code could look like this:
$('input[type="number"]').blur(function(){
//if field is validation candidate and is invalid alert the validationmessage
if( $.prop( this, 'willValidate' ) && !$.prop( this, 'validity').valid){
alert( $.prop( this, 'validationMessage' );
}
});
Of course using an alert, is a little bit stupid, but makes the code clean. If you want to use webshims lib, there is a showError helper. I have put up a demo here
About the helper method $.webshims.validityAlert.showFor:
showFor requires a dom element jQuery object or selector as first argument. the validationmessage as optional second and the last is a boolean, which will show the message without focusing the field.
精彩评论