Skip to content

Instantly share code, notes, and snippets.

@msh345
Forked from ksolo/form-validator.js
Last active December 22, 2015 09:49
Show Gist options
  • Save msh345/6454668 to your computer and use it in GitHub Desktop.
Save msh345/6454668 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$('form').on('submit', function(event) {
event.preventDefault();
var email = document.sign_up.email.value;
var password = document.sign_up.password.value;
$('#errors').html('')
checkEmail(email);
checkPassword(password);
});
});
var validEmail = /^(([^<>()[\]\\.,;:\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 checkEmail(email) {
if (!validEmail.test(email))
{$('#errors').append('<li>Must be a valid email address</li>')}
}
function checkPassword(password) {
if (!(/\w{8,}/).test(password))
{$('#errors').append('<li>Password must be at least 8 characters long</li>')};
if (!(/[A-Z]/).test(password))
{$('#errors').append('<li>Password must have at least one capital letter</li>')};
if (!(/\d/).test(password))
{$('#errors').append('<li>Password must have at least one number</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