Skip to content

Instantly share code, notes, and snippets.

@LilyMGoh
Forked from ksolo/form-validator.js
Created September 5, 2013 18:20
Show Gist options
  • Save LilyMGoh/6454038 to your computer and use it in GitHub Desktop.
Save LilyMGoh/6454038 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
var emailPattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var passwordPattern = /^.*(?=.{8,50})(?=.*[A-Z])(?=.*\d).*$/;
$('button').on("click", function(event){
event.preventDefault();
var email = $('#email').val();
var emailMatch = email.match(emailPattern);
if (emailMatch === null) {
$('#errors').append('<li> Must be a valid email address </li>');
}
var pass = $('#password').val();
var passMatch = pass.match(passwordPattern);
if (passMatch === null) {
$('#errors').append('<li> Password must have at least one numeric character (0-9) </li> \
<li> Password must have at least 8 characters long (0-9) </li> \
<li> Password must have at least one capital character (0-9) </li>');
}
});
});
<!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" id="email" name="email" />
<label for="password">Password</label>
<input type="password" id="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