I wrote some code to validate a form, I'm using live validation, as the user types, here is the snippet that I wrote just for the live validation, but I think I'm repeating too much and I'm looking for some advices:
$('form input').focus(function(){
var inp = $(this).attr('name');
switch(inp)
{
case 'password2':
var theIn = $(this).parent().prev().find('input');
if(!theIn.val() != '')
{
theIn.addClass('error');
}else{
theIn.removeClass('error');
}
var theInp = $(this).parent().prevAll().find('input,select');
theInp.each(function(){
if((!$(this).val()) || ($(this).val() == '-1'))
{
$(this).addClass('error');
}else{
$(this).removeClass('error');
}
});
break;
default:
//Find all previous inputs and see if they are OK
var theInp = $(this).parent().prevAll().find('input,select');
theInp.each(function(){
if((!$(this).val()) || ($(this).val() == '-1'))
{
$(this).addClass('error');
}else{
$(this).removeClass('error');
}
});
}
});
/*
* Register front on keypress
*/
$('form input,form select').each(function(){
//Select <select>
$(this).change(function(){
if($(this).val() == '-1')
{
$(this).addClass('error');
}else{
$(this).removeClass('error');
}
});
$(this).keyup(function(e){
var type = $(this).attr('name');
$(this).parent().find('span.preloader').css('visibility','hidden');
switch(type)
{
case 'email':
var pattern = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
if(!$(this).val().match(pattern))
{
$(this).addClass('error');
}else{
$(this).removeClass('error');
}
break;
case 'password2':
if($(this).val() != $(this).parent().prev().find('input').val())
{
$(this).addClass('error');
$(this).parent().prev().find('input').addClass('error');
}else{
$(this).removeClass('error');
$(this).parent().prev().find('input').removeClass('error');
}
break;
case 'password':
if($(this).val() == $(this).parent().next().find('input').val())
{
$(this).parent().next().find('input').removeClass('error');
$(this).removeClass('error');
}else{
$(this).addClass('error');
}
return true;
break;
default:
if((!$(this).val()) || ($(this).val() == '-1'))
{
$(this).addClass('error');
}else{
$(this).removeClass('error');
}
}
});
});