Created
May 1, 2013 02:35
-
-
Save robotlolita/5493405 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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