Skip to content

Instantly share code, notes, and snippets.

@nlprater
Forked from ksolo/form-validator.js
Last active December 22, 2015 09:48
Show Gist options
  • Save nlprater/6454330 to your computer and use it in GitHub Desktop.
Save nlprater/6454330 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$('form > button').on("click", function(event){
event.preventDefault();
});
$('form > button').on("click", function(){
$('li').hide();
});
$('form > button').on("click",
function validateForm() {
var emailSubmission = document.forms["sign_up"]["email"].value;
var passwordSubmission = document.forms["sign_up"]["password"].value;
var emailPattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
var passwordNumericPattern = /.*[0-9].*/;
var passwordUpcasePattern = /^([\p{Lu}\p{Lt}]\p{Ll}+)+$/;
if (emailSubmission.match(emailPattern) === null){
$('#errors').append('<li>Email must be valid.</li>');
}
if (passwordSubmission.length < 8){
$('#errors').append('<li>Password must be at least 8 characters.</li>');
}
if (passwordSubmission.match(passwordNumericPattern) === null){
$('#errors').append('<li>Password must have at least one number.</li>');
}
if (passwordSubmission.match(passwordUpcasePattern) === null){
$('#errors').append('<li>Password must have at least one capital letter.</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>
</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