diff --git a/tasks/calc/formValidation.js b/tasks/calc/formValidation.js index 0d82e69..77f2903 100644 --- a/tasks/calc/formValidation.js +++ b/tasks/calc/formValidation.js @@ -1,23 +1,33 @@ -// Example starter JavaScript for disabling form submissions if there are invalid fields -document.addEventListener("DOMContentLoaded", () => { - "use strict"; +"use strict"; - // Fetch all the forms we want to apply custom Bootstrap validation styles to +document.addEventListener("DOMContentLoaded", () => { + const _switch = document.getElementById("clientSideValidate"); + _switch.addEventListener("change", () => + _switch.checked ? addValidation() : removeValidation() + ); +}); + +const handler = (event) => { + if (!event.target.checkValidity()) { + event.preventDefault(); + event.stopPropagation(); + } + + event.target.classList.add("was-validated"); +}; + +const addValidation = () => { const forms = document.querySelectorAll(".needs-validation"); - // Loop over them and prevent submission Array.from(forms).forEach((form) => { - form.addEventListener( - "submit", - (event) => { - if (!form.checkValidity()) { - event.preventDefault(); - event.stopPropagation(); - } - - form.classList.add("was-validated"); - }, - false - ); + form.addEventListener("submit", handler, false); }); -}); +}; + +const removeValidation = () => { + const forms = document.querySelectorAll(".needs-validation"); + + Array.from(forms).forEach((form) => { + form.removeEventListener("submit", handler, false); + }); +}; diff --git a/tasks/calc/index.php b/tasks/calc/index.php index e11b0aa..abeea82 100644 --- a/tasks/calc/index.php +++ b/tasks/calc/index.php @@ -19,8 +19,6 @@ include_once "../../base/headers.php"; Headers::html(); - $result = ""; - if ( isset($_POST["operand1"], $_POST["operand2"], $_POST["operator"]) && is_numeric($_POST["operand1"]) && @@ -49,13 +47,32 @@ $result = $operand1 / $operand2; break; } + } else if (isset($_POST["firstLoad"])) { + $errors = []; + + if (!isset($_POST["operand1"])) + array_push($errors, "Operand 1 not set"); + else if (!is_numeric($_POST["operand1"])) + array_push($errors, "Operand 1 not numeric"); + + if (!isset($_POST["operand2"])) + array_push($errors, "Operand 2 not set"); + else if (!is_numeric($_POST["operand2"])) + array_push($errors, "Operand 2 not numeric"); + + if (!isset($_POST["operator"])) + array_push($errors, "No operator chosen"); } ?> +