I've been attempting to integrate input validation functions with the submit function to create a fully functional and straightforward contact form that reacts appropriately to both correct and incorrect input types, as well as empty fields. I'm using Bootstrap 4 and have read the documentation on validation, but am baffled as to why the contact form still gets sent even if only one field is filled out and it doesn't require an email address :/. As a beginner in JS, I'm struggling to figure this out and it's been frustrating me - stuck at this for 8 hours. The commented code in the script.js file is there because I've been trying to combine various functionalities.
Is there anyone willing to rewrite these functions for me?
Below is the code for the form:
'use strict';
//---------Contact form SEND-----------
window.addEventListener("DOMContentLoaded", function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// get the form elements defined in your form HTML above
var form = document.getElementById("bootstrapForm");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error fn-s after form submission
function success() {
form.reset();
status.classList.add("success");
status.innerHTML = "Message has been successfully sent.";
}
function error() {
status.classList.add("error");
status.innerHTML = "There was a problem sending the message";
}
var validation = Array.prototype.filter.call(forms, function(form) {
// handle the form submission event
form.addEventListener('submit', function(e) {
if (form.checkValidity() === false) {
e.preventDefault();
e.stopPropagation();
var data = new FormData(form);
ajax(form.method, form.action, data, success, error);
}
form.classList.add('was-validated');
}, false);
});
}, false);
// helper function for sending an AJAX request
function ajax(method, url, data, success, error) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
success(xhr.response, xhr.responseType);
} else {
error(xhr.status, xhr.response, xhr.responseType);
}
};
xhr.send(data);
}
$(function()
{
// Contact forms
"use strict";
// Detect when form-control inputs are not empty
$(".cool-b4-form .form-control").on("input", function() {
if ($(this).val()) {
$(this).addClass("hasValue");
} else {
$(this).removeClass("hasValue");
}
});
});
Visit my website (with the form located at the bottom) to see it in action: https://marekcmarko.sk