jquery - Input Validation - Style -


http://jsfiddle.net/dm6hm/23/ know if it's possible validate style of input should happen once click onto input field, meaning background color returns it's default white colour after i've finished typing , click somewhere else. far it's able receive data , validate information correctly won't reset white background if click anywhere else.

<input type="email" class="email" value="email"/> <input type="text" class="fname" value="first name"/>  function isemail(email){     var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;     return reg.test(email); }  $(".email").keydown(function(e) {     var $test = $(this).css("background-color", "");     if (isemail($test.val())) {     settimeout(function() {         $test.css("background-color", "green").focus();     }, 0);     }else{     settimeout(function() {         $test.css("background-color", "red").focus();     }, 0);     } });  function isfname(text){     var reg = /^[a-z ,.'-]+$/i;     return reg.test(text); }  $(".fname").keydown(function(e) {     var $test = $(this).css("background-color", "");     if (isemail($test.val())) {         settimeout(function() {             $test.css("background-color", "green").focus();         }, 0);      }else{         settimeout(function() {             $test.css("background-color", "red").focus();         }, 0);     } }); 

as said in comment don't see reason use settimeout highlight background. can directly. also, can use blur() reset background.

this example email field, can same first name:

$(".email").keyup(function(e) {     var $test = $(this);     if (isemail($test.val())) {         $test.css("background-color", "green");     } else {         $test.css("background-color", "red");     } }).blur(function(e) {     $(this).css("background-color", "");   }); 

here fixed fiddle: http://jsfiddle.net/dm6hm/28/


Comments