我从“验证-自定义样式”部分的example in the docs开始创建了一个表单。我在集合输入中添加了“必需”属性,并且验证工作进行得很顺利。现在,我需要向必须遵守特定格式的字段添加自定义验证。
我创建了validaForm()函数来验证该字段并向其中添加“无效”类输入。我需要有关如何在Bootstrap示例提供的代码***中使用该功能的帮助:
// My custom function to validate the field
function validaForm() {
var $inputs = $("#frmIscrCant :input:not([readonly])");
//var values = {};
$inputs.each(function () {
//values[this.id] = $(this).val();
if ($(this).hasClass("partIVAInput") && $(this).val().trim() != "")
if (!isValidPIVA($(this).val())) {
$(this).addClass("is-invalid");
alert("P.IVA non valida!");
}
});
}
// Code provided by Bootstrap example(***). In this function I need to insert the function above
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
validaForm(); // !!!
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>