Skip to content

Instantly share code, notes, and snippets.

@benneuman
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Save benneuman/8850798 to your computer and use it in GitHub Desktop.
Save benneuman/8850798 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
grr = null;
$(function(){
//Your code...
$("#sign_up_form").on("submit", function (event) {
$("ul").hide();
$("ul li").hide();
var password = $(event.target.password).val();
var errors = check_pw(password);
var email = $(event.target.email).val();
if (bad_email(email)) {
errors.push("email");
}
if (errors.length > 0) {
event.preventDefault();
show_errors(errors);
}
else {
return true;
}
})
})
var r_min_length = 8;
var r_capital = new RegExp(/[A-Z]/);
var r_numeric = new RegExp(/\d/);
var r_email = new RegExp(/([a-z]|[A-Z])+@([a-z]|[A-Z])+.([a-z]|[A-Z]){2,}/);
function show_errors(errors) {
$("#errors").show();
for (i = 0; i < errors.length; i++) {
$("#" + errors[i]).show();
}
}
function check_pw(pw) {
var errors = [];
console.log(pw);
if (no_capitals(pw)) {
errors.push("capital");
}
if (no_numbers(pw)) {
errors.push("numeric");
}
if (bad_length(pw)) {
errors.push("length");
}
return errors;
}
function no_capitals(pw) {
return (/[A-Z]/.exec(pw) == null);
}
function no_numbers(pw) {
return (/\d/.exec(pw) == null);
}
function bad_email(email) {
return (/([a-z]|[A-Z])+@([a-z]|[A-Z])+.([a-z]|[A-Z]){2,}/.exec(email) == null)
}
function bad_length(pw) {
return (pw.length < 8);
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="main.css">
<title>Form Validation</title>
</head>
<body>
<form name="sign_up" action="#" method="post" id="sign_up_form">
<label for="email">Email</label>
<input type="text" name="email" />
<label for="password">Password</label>
<input id="pw" type="password" name="password" />
<button type="submit">Sign Up</button>
<ul id="errors">
<li id="email">
Must be a valid email address
</li>
<li id="capital">
Password must contain at least one capital letter
</li>
<li id="numeric">
Password must have at least one numeric character
</li>
<li id="length">
Password must be at least 8 characters long
</li>
</ul>
</form><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="form-validator.js"></script>
</body>
</html>
ul#errors {
color: red;
}
ul#errors {
display: none;
}
ul#errors li {
display: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment