0
0
mirror of https://github.com/twbs/bootstrap.git synced 2024-11-29 11:24:18 +01:00

Tweak form validation snippet. (#29359)

* remove load event
* use `forEach` and `querySelectorAll`
* simplify check
This commit is contained in:
XhmikosR 2019-09-03 18:04:11 +03:00 committed by GitHub
parent d0affaa2ec
commit db002902da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 16 deletions

View File

@ -2,14 +2,14 @@
(function () { (function () {
'use strict' 'use strict'
window.addEventListener('load', function () { // Fetch all the forms we want to apply custom Bootstrap validation styles to
// Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.querySelectorAll('.needs-validation')
var forms = document.getElementsByClassName('needs-validation')
// Loop over them and prevent submission // Loop over them and prevent submission
Array.prototype.filter.call(forms, function (form) { Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) { form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) { if (!form.checkValidity()) {
event.preventDefault() event.preventDefault()
event.stopPropagation() event.stopPropagation()
} }
@ -17,5 +17,4 @@
form.classList.add('was-validated') form.classList.add('was-validated')
}, false) }, false)
}) })
}, false)
})() })()

View File

@ -103,22 +103,24 @@ Custom feedback styles apply custom colors, borders, focus styles, and backgroun
<script> <script>
// Example starter JavaScript for disabling form submissions if there are invalid fields // Example starter JavaScript for disabling form submissions if there are invalid fields
(function() { (function () {
'use strict'; 'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to // Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation'); var forms = document.querySelectorAll('.needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) { // Loop over them and prevent submission
form.addEventListener('submit', function(event) { Array.prototype.slice.call(forms)
if (form.checkValidity() === false) { .forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
} }
form.classList.add('was-validated'); form.classList.add('was-validated');
}, false); }, false);
}); });
}, false);
})(); })();
</script> </script>
{{< /example >}} {{< /example >}}