Skip to content

Instantly share code, notes, and snippets.

@CharlieTruong
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Save CharlieTruong/8848392 to your computer and use it in GitHub Desktop.
Save CharlieTruong/8848392 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$("button").click(function(e){
e.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
checkError(email, password);
});
});
var checkError = function(email, password){
$("#errors").empty();
validateEmail(email);
validatePasswordLength(password);
validateCapital(password);
validateNumber(password);
if ($("#errors li").length === 0){
$("#errors").append("<li>There are no errors! Congrats</li>");
}
}
var validateEmail = function(email) {
var validFormat = /^(([^<>()[\]\\.,;:\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,}))$/;
if (validFormat.test(email)){
return true;
}
else{
$("#errors").append("<li>This is an invalid email.</li>");
return false;
}
}
var validatePasswordLength = function(password){
if(password.length < 8){
$("#errors").append("<li>The password must contain at least 8 characters.</li>");
return false;
}
else{
return true;
}
}
var validateCapital = function(password){
var validFormat = /[A-Z]/;
if (validFormat.test(password)){
return true;
}
else{
$("#errors").append("<li>Your password must have at least one capital letter.</li>");
return false;
}
}
var validateNumber = function(password){
var validFormat = /[0-9]/;
if (validFormat.test(password)){
return true;
}
else{
$("#errors").append("<li>Your password must have at least one number.</li>");
return false;
}
}
<!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" id="email" />
<label for="password">Password</label>
<input type="password" name="password" id="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