Skip to content

Instantly share code, notes, and snippets.

@tubbo
Forked from robotlolita/form-validation.js
Last active December 20, 2015 06:09
Show Gist options
  • Select an option

  • Save tubbo/6083542 to your computer and use it in GitHub Desktop.

Select an option

Save tubbo/6083542 to your computer and use it in GitHub Desktop.
// Validates a single input
function validate(input) {
if (!input.getAttribute('required')) { return false; }
(!input.value) ? new Error(input.name + "is required.") : true
}
// Takes in an array of inputs, and tells us if they're all valid or no
function isFormInvalid(inputs) {
return inputs.map(validate) // Validates all fields
.filter(Boolean) // Keeps only the errors
.length > 0 // Checks if we still have any errors
}
// When submitting, we check if the form is valid
form.addEventListener('submit', function(ev) {
var fields = form.querySelectorAll('input')
return !isFormInvalid(fields)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment