Skip to content

Instantly share code, notes, and snippets.

@jpark3000
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Save jpark3000/8849709 to your computer and use it in GitHub Desktop.
Save jpark3000/8849709 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
var emailPattern = /.+\@.+\..+/;
var pwdCapitalPattern = /[A-Z]/;
var pwdNumPattern = /\d/;
function checkEmail(email) {
return emailPattern.test(email);
};
function emailError() {
$('#errors').append('<li>Must be a valid email address</li>');
};
/////////////////////////////////////////////////////////
function checkPwdLength(pwd) {
return pwd.length < 8;
};
function pwdLengthError() {
$('#errors').append('<li>Password must be at least 8 characters long</li>');
};
///////////////////////////////////////////////////////// 
function checkPwdCapital(pwd) {
return pwdCapitalPattern.test(pwd)
};
function pwdCapitalError() {
$('#errors').append('<li>Password must have at least one capital letter</li>');
};
///////////////////////////////////////////////////////////
function checkPwdNum(pwd) {
return pwdNumPattern.test(pwd)
};
function pwdNumError() {
$('#errors').append('<li>Password must have at least one capital character(0-9)</li>');
};
/////////////////////////////////////////////////////////
function clearErrors() {
$('#errors').html('');
};
$('form').submit(function() {
event.preventDefault;
var errors = [];
var email = $('input[name="email"]').val();
var password = $('input[name="password"]').val();
if (!(checkEmail(email))) {
errors.push(emailError);
};
if (checkPwdLength(password)) {
errors.push(pwdLengthError);
};
if (!(checkPwdCapital(password))) {
errors.push(pwdCapitalError);
};
if (!(checkPwdNum(password))) {
errors.push(pwdNumError);
};
if (errors.length > 0) {
clearErrors();
for (var i in errors) {
errors[i]();
};
return false;
} else {
return true;
};
});
});
<!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