Skip to content

Commit

Permalink
Move logic into a validate function
Browse files Browse the repository at this point in the history
- Moved away from automatically handling for submissions since we can't guarantee event order
- Added a public validate and onValidSubmit function wrapper
- Updated the example
  • Loading branch information
atogle committed Nov 22, 2013
1 parent 255edc1 commit a901790
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 11 deletions.
7 changes: 7 additions & 0 deletions example.html
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,12 @@

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="gatekeeper.js"></script>
<script>
$('form').on('submit', Gatekeeper.onValidSubmit(function(evt) {
alert('valid!');
}, function(evt) {
alert('invalid!');
}));
</script>
</body>
</html>
2 changes: 1 addition & 1 deletion gatekeeper.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
.form-submitted input:invalid,
.form-submitted textarea:invalid,
.form-submitted select:invalid {
border: 1px solid #b2182b;
border: 2px solid #b2182b;
}
33 changes: 23 additions & 10 deletions gatekeeper.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,36 @@ var Gatekeeper = {};
return invalidEls;
};

// Bind to all forms in the document, forever
$(document).on('submit', 'form', function(evt) {
evt.preventDefault();

NS.validate = function(form) {
// Get invalid elements from the form
var invalidEls = NS.getInvalidFormEls(this);
var invalidEls = NS.getInvalidFormEls(form);

// Indicate that this form has been submitted
$(this).addClass('form-submitted');
$(form).addClass('form-submitted');

if (invalidEls && invalidEls.length > 0) {
// Stops the submit event from triggering anywhere else
evt.stopImmediatePropagation();

// Focus on the first invalid element
invalidEls[0].focus();
if (invalidEls[0].select) { invalidEls[0].select(); }

return false;
}
});
return true;
};

NS.onValidSubmit = function(success, error) {
return function(evt) {
evt.preventDefault();

if (NS.validate(evt.target)) {
if (success) {
success.call(this, arguments);
}
} else {
if (error) {
error.call(this, arguments);
}
}
};
};
}(Gatekeeper));

0 comments on commit a901790

Please sign in to comment.