Home > Back-end >  add customized field for bootstrap validation modal
add customized field for bootstrap validation modal

Time:04-03

i'm using bootstrap's form validation to validate a form. i wan to add an extra field called discount code. this field should accept only specified codes. when the field is empty it should light green, when the code is right it should light green and when the code is wrong it should light red. how can i do that using the bootstrap form validation?

thats how my form almost looks like

<form  novalidate>
   <div >
      <div >
       <strong>Enter your name </strong>
       <input type="text" name="name" id="name"  value="" required minlength="3" />
       <div >
           Name should be at least 3 characters
       </div>
     </div>
    </div>

  <div >
    <button  type="submit">Submit form</button>
  </div>
</form>
<script>
(function () {
  'use strict'

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
})()
</script>

CodePudding user response:

use input pattern in combination with checkValidity()

    function testInput(that){    
          alert(that.checkValidity());
    }
<input type="text" pattern="xyz" onchange="testInput(this)">

CodePudding user response:

just add the class "needs-validation" for each input. I have replace he event to "change" This is userful while typing keys. But if you need by submiting, you can change it to "submit". You also need to replace the css classes

(function () {

 
  var forms = document.querySelectorAll('.needs-validation')


  Array.prototype.slice.call(forms)
    .forEach(function (form) {
     
      form.addEventListener('change', function (event) {
       form.classList.remove('was-validated','error')
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
         form.classList.add('error');
         return
        }
        form.classList.add('was-validated')
      }, false)
    })
})()
 .needs-validation{
border:1px solid black;
}
.was-validated{
border:1px solid green;
}
.error{
border:1px solid red;
}
<input pattern="xyz" >

  • Related