gpt4 book ai didi

javascript - Bootstrap 4 填写表单时实时表单验证

转载 作者:行者123 更新时间:2023-12-02 21:37:46 25 4
gpt4 key购买 nike

我刚刚查看了 Bootstrap 4.4 ( https://getbootstrap.com/docs/4.4/components/forms/#how-it-works ) 中的表单验证部分,并将代码实现到我的项目中,触发验证的代码示例和脚本实现看起来很棒!

我想知道是否可以在用户填写表单时而不是尝试提交表单时实现此验证?

例如,如果我有两个输入,名字和姓氏,这两个输入都是必需的,当我更改为姓氏字段时,我可以触发验证检查以触发我刚刚填写的字段?

例如,即时验证?

我当前的验证(单击表单提交按钮时触发)是:

function validateForm () {
var forms = document.getElementsByClassName('needs-validation')
var validation = Array.prototype.filter.call(forms, function(form) {
console.log(form.checkValidity())
if (form.checkValidity() === false) {
event.preventDefault()
event.stopPropagation()

// get the "first" invalid field
var errorElements = document.querySelectorAll('.form-control:invalid')

// scroll the user to the invalid field
window.scrollTo(0, getOffset(errorElements[0]).top)

}
form.classList.add('was-validated')
})
}

最佳答案

checkValidity() 函数也适用于单个输入。将 blur 处理程序绑定(bind)到每个输入,然后在验证后将类 is-valid/is-invalid 添加到每个输入...

(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom validation styles
var inputs = document.getElementsByClassName('form-control')

// Loop over each input and watch blue event
var validation = Array.prototype.filter.call(inputs, function(input) {

input.addEventListener('blur', function(event) {
// reset
input.classList.remove('is-invalid')
input.classList.remove('is-valid')

if (input.checkValidity() === false) {
input.classList.add('is-invalid')
}
else {
input.classList.add('is-valid')
}
}, false);
});
}, false);
})()

https://codeply.com/p/mzBNbAlOvQ

关于javascript - Bootstrap 4 填写表单时实时表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60448001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com