Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created May 1, 2013 02:35
Show Gist options
  • Select an option

  • Save robotlolita/5493405 to your computer and use it in GitHub Desktop.

Select an option

Save robotlolita/5493405 to your computer and use it in GitHub Desktop.
// Validates a single input
function validate(input) {
return !input.getAttribute('required')? false // not required, no validation
: !input.value? new Error(input.name + ' is required.')
: /* otherwise */ false // properly filled
}
// 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