Skip to content

Instantly share code, notes, and snippets.

@thejessleigh
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Save thejessleigh/9258142 to your computer and use it in GitHub Desktop.
Save thejessleigh/9258142 to your computer and use it in GitHub Desktop.
Form Validation
$(function() {
$('form').on('submit', function(event) {
errors = []
function validateForm(email, password) {
console.log(email + " " + password)
function validateEmail(email) {
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
errors.push("Not a valid e-mail address");
}
}
function validatePassword(password) {
if (password.match(/[0-9]/) === null) {
errors.push("Password must contain at least one numerical value.");
}
if (password.match(/[A-Z]/) === null) {
errors.push("Password must contain at least one capital letter.");
}
if (password.length < 8) {
errors.push("Password must be at least eight characters long.");
}
}
validateEmail(email)
validatePassword(password)
}
event.preventDefault()
var data = $('form').serializeArray();
validateForm(data[0].value, data[1].value);
// console.log(errors)
function checkErrors(event) {
console.log(errors)
if (errors.length > 0) {
$.each(errors, function(i, error) {
$('#errors').append('<li>' + error + '</li>');
})
}
}
checkErrors()
})
});
<!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