Skip to content

Instantly share code, notes, and snippets.

@jespr
Created February 15, 2019 06:57
Show Gist options
  • Save jespr/048aea95a1236e3c0de424168a32f4d3 to your computer and use it in GitHub Desktop.
Save jespr/048aea95a1236e3c0de424168a32f4d3 to your computer and use it in GitHub Desktop.
Javascript form validation
<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