Skip to content

Instantly share code, notes, and snippets.

@Lyonsclay
Forked from ksolo/form-validator.js
Last active December 27, 2015 17:19
Show Gist options
  • Save Lyonsclay/7361002 to your computer and use it in GitHub Desktop.
Save Lyonsclay/7361002 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
//Your code...
$("form").on("submit", function(event){
event.preventDefault();
var email = $('form input[name="email"]').val()
var password = $('form input[name="password"]').val()
var email_format = /.+@.+\..+/
var one_digit = /\d+/
var one_cap = /[A-Z]+/
var eight_chars = /.{8}/
if (email_format.exec(email) === null) {
$("ul#errors").append("<li>Must be a valid email address.</li>");
}
if (one_digit.exec(password) === null) {
$("ul#errors").append("<li>Password must have at least one number.</li>");
}
if (one_cap.exec(password) === null) {
$("ul#errors").append("<li>Password must have at least one capital letter.</li>");
}
if (eight_chars.exec(password) === null) {
$("ul#errors").append("<li>Password must have at least eight characters.</li>");
}
});
});
<!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><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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment