Code: Select all
// Initialize form validation
const initializeFormValidation = () => {
"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
);
});
};
initializeFormValidation();
// Reset form validation
$("#reset-button").on("click", () => {
$("#test-form").removeClass("was-validated");
$("#test-form").addClass("needs-validation");
});< /code>
/* Required Fields */
.required-field::after {
content: "*";
color: red;
margin-left: 2px;
}
.required-field-margin-left::after {
content: "*";
color: red;
margin-left: -2px;
}
form {
padding-left: 10px;
padding-top: 12px;
}
#help-text {
width: 550px;
margin-bottom: 1rem;
}< /code>
First, hit the submit form button to see the form validation stop form submission.
Then, click into the textarea box and hit enter.
You'll see the form validator say that the newline character is valid, when it is not.
Please enter a value.
Submit form
Reset form