Skip to content

Instantly share code, notes, and snippets.

@ctailor2
Forked from ksolo/form-validator.js
Last active December 28, 2015 01:49
Show Gist options
  • Save ctailor2/7423896 to your computer and use it in GitHub Desktop.
Save ctailor2/7423896 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$("form").on("submit", function(){
event.preventDefault();
var password = $(this).find(":nth-child(4)").val()
var errors = validatePassword(password);
$.each(errors, function(index, value){
$("#errors").append("<li>" + value + "</li>");
});
});
function validatePassword(password){
var cap_re = /.*[A-Z]+.*/
var num_re = /.*[0-9]+.*/
var errors = []
if (!password.match(num_re)) {
errors.push("Password must have at least one numeric character (0-9)")
}
if (!password.match(cap_re)) {
errors.push("Password must have at least one capital letter")
}
if (password.length < 8) {
errors.push("Password must be at least 8 characters long")
}
return errors
}
});
<!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" />
<input type="submit" value="Sign Up"/>
<ul id="errors"></ul>
</form><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" 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