Skip to content

Instantly share code, notes, and snippets.

@chriswright47
Forked from ksolo/form-validator.js
Last active December 27, 2015 17:49
Show Gist options
  • Save chriswright47/7365171 to your computer and use it in GitHub Desktop.
Save chriswright47/7365171 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$('form').submit(function(event) {
var prevent = false
var valid_email = /\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\b/;
if (!(valid_email.test($('form input')[0].value))) {
prevent = true;
$('#errors').append('<li>Must be a valid email address</li>');
}
if (!(/\d/.test($('form input')[1].value))) {
$('#errors').append('<li>Password must have at least one numeric character</li>');
prevent = true;
}
if (!(/[A-Z]/.test($('form input')[1].value))) {
$('#errors').append('<li>Password must have at least one capital letter</li>');
prevent = true;
}
if (($('form input')[1].value).length < 8) {
$('#errors').append('<li>Password must have at least eight characters</li>');
prevent = true;
}
if (prevent) {
event.preventDefault();
}
})
//Your code...
});
<!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" class='email'/>
<label for="password">Password</label>
<input type="password" name="password" class='password' />
<button class='submit' 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