Skip to content

Instantly share code, notes, and snippets.

@mehagel
Forked from ksolo/form-validator.js
Last active December 21, 2015 03:29
Show Gist options
  • Save mehagel/6242700 to your computer and use it in GitHub Desktop.
Save mehagel/6242700 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$('form').on('click', function(e) {
e.preventDefault();
var errors = [];
// email verification
var x=document.forms["sign_up"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
errors.push("Must be a valid e-mail address.");
}
// p = password pulled from form
var p = document.forms["sign_up"]['password'].value;
// verifies length
var length = p.length;
if (length < 8) {
errors.push("Password must be at least 8 characters long.");
}
//verifies one capital letter
var capital_pattern = /^(?=.*[A-Z])/;
if (! p.match(capital_pattern)) {
errors.push("Password must contain at least 1 capital letter.");
}
//verifies one numeric character
var numeric_pattern = /^(?=.*\d)/;
if (! p.match(numeric_pattern)) {
errors.push("Password must contain at least 1 numeric character (0-9).");
}
var newHTML = [];
for (var i = 0; i < errors.length; i++){
newHTML.push('<li>' + errors[i] + '</li>');
}
$('#errors').html(newHTML);
});
});
// to just verify password but not identifying indivudal aspects with
// different errors so didn't use
// ((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})
<!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