Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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('<spanstyle="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.

Solution 2:

An approach utilizing HTML5required, pattern attributes; CSScounter, :invalid , :valid, :not(), ::after , content, general sibling selector ~

body {
  counter-reset: err;
  counter-reset: err2;
  counter-increment: err2 2;
}
.fs-error {
  display: none;
}
input:not(:invalid) {
  border-bottom: 2px solid rgb(0, 102, 0);
}
input:invalid {
  border-bottom: 2px solid red;
}
input:invalid ~ .fs-error {
  display: block;
  position: relative;
  top: -70px;
  color: red;
}
input:nth-of-type(1):invalid ~ input:valid ~ .fs-error::after {
  counter-increment: err;
  content: "Error "counter(err);
}
input:nth-of-type(1):valid ~ input:nth-of-type(2):invalid ~ .fs-error::after {
  counter-increment: err 2;
  content: "Error "counter(err);
}
input:nth-of-type(1):invalid ~ input:nth-of-type(2):invalid ~ .fs-error::after {
  counter-increment: err;
  content: "Error "counter(err)", Error "counter(err2);
}
<fieldsetdata-check-id="1"><br>1
  <inputtype="text"size="50"id="ptitle"name="title"minlength="1"pattern="\w+"required/><br>2
  <inputtype="text"id="address"name="p_address"minlength="1"pattern="\w+"required/><divclass="fs-error"><span></span></div></fieldset>

Post a Comment for "Jquery Custom Validation Displays Only Error Of Last Field"