Skip to content

Instantly share code, notes, and snippets.

@KevinFalank
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Save KevinFalank/8850780 to your computer and use it in GitHub Desktop.
Save KevinFalank/8850780 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$('form').submit(function(e){
e.preventDefault();
var emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i;
var passwordRegex = /^(?=.*\d)(?=.*[A-Z])\w{8,}$/
var formData = $('form').serializeArray();
var errorFound = false;
$('#errors').empty();
for (var i = 0; i < formData.length; i++) {
switch(formData[i].name)
{
case "email":
var match = emailRegex.exec(formData[i].value);
if (! match) {
errorFound = true;
$('#errors').append('<li>Must be a valid email address</li>');
}
break;
case "password":
console.log("case password");
var match = passwordRegex.exec(formData[i].value);
if (! match) {
errorFound = true;
$('#errors').append('<li>Password must have at least one numeric character(0-9)</li>');
$('#errors').append('<li>Password must have at least one capital letter</li>');
$('#errors').append('<li>Password must have at least 8 characters long</li>');
}
break;
}
}
return errorFound
})
});
<!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