Skip to content
Advertisement

JQuery Validator with custom .addMethod over Bootstrap gives problems when was-validated class is active

I’m having some troubles with Bootstrap 5 and JQuery Validator with custom class.

Seems it works separately from Bootstrap.

In this method for checking hex validity (optional) the .was-validated form class generates problems.

jQuery.validator.addMethod("isvalidhex", function(value, element) {
    return this.optional(element) || value.match(/^#[a-f0-9]{6}$/i) !== null;
}, "Must be a valid hex");

Here my code

<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<style>form * { text-align:center; }</style>


<form method="POST" class="needs-validation" id="formAA" novalidate="novalidate">

<div class="mb-3">
  <label for="a" class="form-label">A</label>
  <input type="text" class="form-control form-control-lg text-center" id="a" name="a" maxlength="100" required="">
</div>
<div class="divdropdowncolor mb-3 text-center">
  <label for="selectcolor" class="form-label">B</label><br>
  <input class="form-control form-control-lg" type="color" id="selectcolor" name="selectcolor" value="#0AF000" style="display:inline-block; width:48%; vertical-align: middle; float:left;">
  <input type="text" class="form-control form-control-lg text-center error" id="selectcolorB" name="selectcolorB" placeholder="#FFFFFF" maxlength="7" style="display:inline-block; width:48%; vertical-align: middle; float:right;" col="7" aria-invalid="true">
</div>
<div class="mb-3" style="clear:both;"></div>
<button type="submit" class="btn btn-primary form-control-lg" style="width:100%;">Submit</button>
</form>
<!-- scripts -->
<script>
function isValidColor(str) { return str.match(/^#[a-f0-9]{6}$/i) !== null; }
$(document).ready(function() {
    $('#selectcolorB').val($('#selectcolor').val());
});
$('#selectcolor').on('change', function (event) { $('#selectcolorB').val($('#selectcolor').val()); });
$('#selectcolorB').on('change', function (event) { if( isValidColor($('#selectcolorB').val()) ) { $('#selectcolor').val($('#selectcolorB').val()); } });
</script>

<script>
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});

jQuery.validator.addMethod("isvalidhex", function(value, element) {
    return this.optional(element) || value.match(/^#[a-f0-9]{6}$/i) !== null;
}, "Must be a valid hex");

$('#formAA').validate({

  rules: {
    selectcolorB : { isvalidhex : true },
    bgcolor : { isvalidhex : true }
  },
  submitHandler: function(form, e) {
    console.log('The form is valid and would have been submitted successfully');
  }
});
</script>

<script>
(function () {
  'use strict'
  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()) {
            //form.classList.remove('was-validated')
          event.preventDefault()
          event.stopPropagation()
        }

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

It’s more complicated said than done.

So go use fiddle

https://jsfiddle.net/qmsjo3L7/

Insert in the second input a wrong hex, like (wekdne).

You got the error Must be a valid hex.

If you click over the submit button you can see that the errors are recognized

1) This field is required.
2) Must be a valid hex

but the inputs colors are red for the normal method (input a) and green for the custom method.

Also, if you edit the inputs, the custom method works when the input is changed (keyup or keydown, I don’t know) but the normal method works only on submit.

There’s someone more able than me that can solve this?

Click on submit

Advertisement

Answer

The last <script> block adds an additional submithandler which is causing odd results. Remove that and things immediately improve.

Bootstrap usage is demonstrated at https://github.com/jquery-validation/jquery-validation/blob/master/demo/bootstrap/index-bs4.html, and live demo available at https://jqueryvalidation.org/files/demo/bootstrap/index.html

Implement the errorElement, errorPlacement, highlight and unhighlight directives shown in the above demo and it works as you expect: https://jsfiddle.net/bytestream/dekzfxns/2/

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement