Skip to content

Instantly share code, notes, and snippets.

@markmccanna1
Forked from ksolo/form-validator.js
Last active December 21, 2015 03:39
Show Gist options
  • Save markmccanna1/6243920 to your computer and use it in GitHub Desktop.
Save markmccanna1/6243920 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
//Your code...
$('form').on('submit', function(event) {
event.preventDefault();
var array = $('form').serializeArray();
// console.log(array)
//prints out the email from the form
// console.log( array[0].value );
var email = array[0].value;
var password = array[1].value;
var emailPat = /\D+@\D+\.\D{3,}/;
var passPat = /(.*[A-Z]+.*[0-9].*|.*[0-9].*[A-Z]+.*)/;
if ( !emailPat.test(email)) {
//show some error message
//add a list item to the error ul
$('<li>Must be a valid email address </li>').appendTo('#errors');
}
if( !passPat.test(password) || password.length < 8) {
//show another error message
//add a list item to the error ul
$('<li>Passwords must have at least one number </li>').appendTo('#errors');
$('<li>Passwords must have at least one capital letter </li>').appendTo('#errors');
$('<li>Passwords must be at least characters </li>').appendTo('#errors');
}
//send ajax to the server
});
});
<!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