Skip to content

Instantly share code, notes, and snippets.

@leeacto
Forked from ksolo/form-validator.js
Last active December 22, 2015 09:39
Show Gist options
  • Save leeacto/6453186 to your computer and use it in GitHub Desktop.
Save leeacto/6453186 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
//Your code...
$('button').click(function(event) {
var email = $('#email').val();
var pass = $('#password').val();
var errors = new Array;
var em_re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i;
//email valid
if (em_re.exec(email) === null) {
errors.push('Must be a valid email address');
}
//1 number in password
if (/\d/.exec(pass) === null) {
errors.push('Password must have at least one numeric character (0-9)');
}
//1 capital letter in password
if (/[A-Z]/.exec(pass) === null) {
errors.push('Password must have at least one capital letter');
}
//At least 8 character pass
if (pass.length < 8) {
errors.push('Password must be at least 8 characters long');
}
console.log(errors);
if (errors.length > 0) {
event.preventDefault();
for (var i=0; i < errors.length; i++) {
var node = document.createElement('li');
var textnode = document.createTextNode(errors[i]);
node.appendChild(textnode);
document.getElementById('errors').appendChild(node);
}
}
});
});
<!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 id="email" type="text" name="email" />
<label for="password">Password</label>
<input id="password" 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