Created
February 15, 2019 06:57
-
-
Save jespr/048aea95a1236e3c0de424168a32f4d3 to your computer and use it in GitHub Desktop.
Javascript form validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
document.addEventListener("DOMContentLoaded", function () { | |
var formSelector = 'form'; | |
document.querySelector(formSelector).addEventListener("submit", function (e) { | |
var isValid = true; | |
// Match all fields that have aria-required="true" | |
var requiredFields = document.querySelectorAll("[aria-required='true']") | |
// Loop over all required fields | |
requiredFields.forEach(function (field) { | |
var value = field.value; | |
// Reset the style on the field | |
field.style.border = undefined; | |
// Check if value of the field is empty | |
if (value === "") { | |
isValid = false; | |
// Add a red border to the field that's required | |
field.style.border = "1px solid red"; | |
} | |
}) | |
// Prevent the form from being submitted if not valid | |
if (!isValid) { | |
e.preventDefault(); | |
} | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment