Skip to content

Instantly share code, notes, and snippets.

@oconn
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save oconn/9257696 to your computer and use it in GitHub Desktop.

Select an option

Save oconn/9257696 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$("form").on("submit", function(e){
e.preventDefault();
$("#errors").empty();
var errors = []
var email = $("form input:first").val();
var password = $("form input:last").val();
var password_cap = new RegExp(/.*[A-Z].*/);
var password_num = new RegExp(/.*[0-9].*/);
var emailRegExp = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
function printErrors (element, index, array) {
// console.log(typeof(element)); // string
$("#errors").append("<li>" + element + "</li>");
}
// - The email conforms to the standard pattern
if (!emailRegExp.test(email)) {
errors.push("Invalid Email");
}
// - The password has at least 8 characters
if (password.length < 8) {
errors.push("Password must have 8 characters");
}
// - The password has at least one capital letter
if (!password_cap.test(password)) {
errors.push("Password must have at least one capital letter");
}
// - The password has at least one numeric character
if (!password_num.test(password)) {
errors.push("Password must have at least on number")
}
if (errors.length === 0) {
// Send form
} else {
errors.forEach(printErrors)
}
});
});
// When the user clicks the "Sign Up" button
// They should be notified if any of the following conditions are NOT true
// If any of the above conditions are false
// - The form is not allowed to be submitted
// - Error messages are dislpayed
<!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">
<label for="email">Email</label>
<input type="text" name="email" />
<label for="password">Password</label>
<input type="password" name="password" />
<button type="submit">Sign Up</button>
<ul id="errors"></ul>
</form>
<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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment