Home > front end >  check input on length and use bootstrap validation
check input on length and use bootstrap validation

Time:11-09

I have - I think so - a very simple question. I'm working with Bootstrap 4.6 and I want to have a form-validation for my input.

I need to check if my input has a length of 5 or lower than the validation should be "not fullfiled" (red) otherwise if it's equal or higher than 5 it should be fullfiled, so it should be green.

red: enter image description here

green: enter image description here

I want to have that validation from Bootstrap 4.6 - here is the link to this component: https://getbootstrap.com/docs/4.6/components/forms/#validation

Thanks in advance for helping me out!

Here you can see my code:

<form class="was-validated">
  <div class="mb-3">
    <label for="validationTextarea">Textarea</label>
    <input class="form-control" id="validationTextarea" placeholder="Required example textarea" onkeyup="checkInput()" required></input>
  </div>
</form>
function checkInput() {
  var input = document.getElementById("validationTextarea").value;

  if(input.length < 5) {
    //it should be red
  } else if (input.length >= 5) {
    //it should be green
  }
}

CodePudding user response:

If you want custom validation then you can

1) Remove the was-validated class from the form element, because you want to add custom validation

  <form class="m-3"> 
    <div class="mb-3">
      <label for="validationTextarea">Textarea</label>
      <input class="form-control is-invalid" id="validationTextarea" placeholder="Required example textarea" onkeyup="checkInput()" required></input>
    </div>
  </form>

2) Now comes the logic part, where you have to add is-invalid class if values.length < 5 else add is-valid class.

const input = document.querySelector( "#validationTextarea" );

function checkInput() {
    var value = document.getElementById( "validationTextarea" ).value;

    if ( value.length < 5 ) {
        input.classList.remove( "is-valid" );
        input.classList.add( "is-invalid" );
    } else {
        input.classList.add( "is-valid" );
        input.classList.remove( "is-invalid" );
    }
}

const input = document.querySelector("#validationTextarea");

function checkInput() {
  var value = document.getElementById("validationTextarea").value;

  if (value.length < 5) {
    input.classList.remove("is-valid");
    input.classList.add("is-invalid");
  } else {
    input.classList.add("is-valid");
    input.classList.remove("is-invalid");
  }
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>


<form class="m-3">
  <div class="mb-3">
    <label for="validationTextarea">Textarea</label>
    <input class="form-control is-invalid" id="validationTextarea" placeholder="Required example textarea" onkeyup="checkInput()" required></input>
  </div>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related