Skip to content

Instantly share code, notes, and snippets.

@rishey
Forked from ksolo/form-validator.js
Last active December 22, 2015 09:58
Show Gist options
  • Save rishey/6455123 to your computer and use it in GitHub Desktop.
Save rishey/6455123 to your computer and use it in GitHub Desktop.
Form Validation
$(document).ready(function(){
console.log(errors);
$(function(){
$("form").on("submit", function(event){
$("#errors").html("");
email = $("input").first().val();
password = $("input").last().val();
validateEmail(email);
validatePassword(password);
event.preventDefault();
});
});
});
function validateEmail(email)
{
var emailRegexp = "[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)"
if (email.match(emailRegexp) === null) {
$("#errors").append("<li>Must be a valid email address.</li>")
}
}
function validatePassword(password)
{
//check for single numeric
var passwordNumberRegexp = "(.*\d)"
if (password.match(passwordNumberRegexp) === null) {
$("#errors").append("<li>Password must have at least one numeric character (0-9)</li>")
}
// check for at least one capital letter
var passwordAlphaRegexp = "(.*[A-Z])"
if (password.match(passwordAlphaRegexp) === null) {
$("#errors").append("<li>Password must have at least one capital letter.</li>")
}
//check for at least 8 len
var passwordLen = "(\S{8,})"
if (password.match(passwordLen) === null) {
$("#errors").append("<li>Password must be at least 8 characters long.</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" 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