Skip to content

Instantly share code, notes, and snippets.

@ltlai
Forked from ksolo/form-validator.js
Last active December 21, 2015 03:58
Show Gist options
  • Save ltlai/6245505 to your computer and use it in GitHub Desktop.
Save ltlai/6245505 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$('button').click(function(e) {
var email = $(':input[name="email"]').val();
var password = $(':input[name="password"]').val();
var errors = []
if (invalidEmail(email)) {
errors.push(invalidEmail(email));
};
if (tooShort(password)) {
errors.push(tooShort(password));
};
if (noCaps(password)) {
errors.push(noCaps(password));
};
if (noNums(password)) {
errors.push(noNums(password));
};
if (errors != []) {
e.preventDefault();
$('#errors').html('');
for(var i=0; i<errors.length; i++) {
$('#errors').append("<li>" + errors[i] + "</li>");
}
}
$(this).unbind('click').click();
});
});
function invalidEmail(email) {
var patt1 = /\w+@\w+.\w{2,}/;
if (!patt1.test(email)) {
return "Must be a valid email address"
}
}
function tooShort(password) {
if (password.length < 8) {
return "Password must be at least 8 characters long"
}
}
function noCaps(password) {
if (password.toLowerCase() === password) {
return "Password must have at least one capital letter"
}
}
function noNums(password) {
var patt2 = /\d+/;
if (!patt2.test(password)) {
return "Password must have at least one numeric character (0-9)"
}
}
<!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