XiLab XiLab - 7 months ago 19
Javascript Question

jQuery custom validation displays only error of last field

I've written the following simple validation code with Jquery, everything is working fine but only the error of last field is displayed.
I've started placing this fieldset with an error div:

<fieldset data-check-id="1">
<div class="fs-error"></div>
<input type="text" size="50" id="ptitle" name="title" />
<input type="text" id="address" name="p_address">
</fieldset>


Next I've tried something like this

function check($fs){
var ok = true;
switch($fs.attr('data-check-id')){
case '1':

$ptitle = $('#ptitle',$fs);
$address = $('#address',$fs);

//title
if ($ptitle.val().length == 0) {
ok=false;
jQuery( "#ptitle" ).css( "border-bottom", "2px solid red" );
jQuery('.fs-error').html('<span style="color:red;"> Error 1 </span>');
jQuery('.fs-error').show();
}
else{
jQuery( "#ptitle" ).css( "border-bottom", "2px solid rgb(0, 102, 0)" );
jQuery('.fs-error').hide();
}

//Address
if ($address.val().length == 0) {
ok=false;
jQuery( "#address" ).css( "border-bottom", "2px solid red" );
jQuery('.fs-error').html('<span style="color:red;"> Error 2 </span>');
jQuery('.fs-error').show();
}
else{
jQuery( "#address" ).css( "border-bottom", "2px solid rgb(0, 102, 0)" );
jQuery('.fs-error').hide();
}
break;
}

if(ok === true){
$fs.attr('data-complete', true);
return true;
}
else{
$fs.attr('data-complete', false);
return false;
}
}


Function for checking

function form_completeCheck(){
var ok = true;
$('fieldset').each(function(index,elem){
$this = $(this);
if ($this.attr('data-complete') != 'true') {
ok = false;
};
})

if (ok === true) {
//go go go..
return true;
}
else{
// stop
return false;
}

}


Now everything is working correctly but if both title and address are not filled it shows only the address error (Error 2). If I insert the address, title input is highlighted with red border but its message is not displayed (Error 1). What I'm doing wrong? Thanks in advance

Answer

When there are 2 errors only second one is showing because you're completely rewriting fs-error div with this line (erasing what was there before):

jQuery('.fs-error').html('<span style="color:red;"> Error 2 </span>');

In your second case Error 1 is not displayed because you're hiding div in your second Address validation:

jQuery('.fs-error').hide();

You want to hide it only if there are no errors.

Comments