Skip to content

Instantly share code, notes, and snippets.

@hyperking
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyperking/0f996fac6b6c5ac74e05 to your computer and use it in GitHub Desktop.
Save hyperking/0f996fac6b6c5ac74e05 to your computer and use it in GitHub Desktop.
form validator
<h3>header</h3>
<form method="POST" id="myform" action="echo/html">
<label for="foo">First Name:</label>
<input type="input" id="foo">
<br>
<label for="bar">Last Name:</label>
<input type="input" id="bar">
<br>
<label for="baz">Email:</label>
<input type="input" id="baz">
<br>
<input type="submit">
</form>
<div id="debugger"></div>
// Place ID's of all required fields here.
var required = ["foo", "bar"],
errmessage = "Please fill out this field.";
$(":input").focus(function(){
if ($(this).hasClass("highlight") ) {
$(this).val("").removeClass("highlight");
}
});
$("#myform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if (input.val() == "" || input.val() == errmessage) {
input.addClass("highlight");
input.val(errmessage);
} else {
input.removeClass("highlight");
}
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("highlight")) {
return false;
} else {
return true;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment