Skip to content

Instantly share code, notes, and snippets.

@CoolJorcz
Forked from ksolo/form-validator.js
Last active December 21, 2015 03:39
Form Validation
// shorthand for $(document).ready();
function validPasswordLength (password) {
if (password.length >= 8) {
return true
}
else {
return "Password must be at least 8 characters long"
}
}
function validEmail(email) {
var re = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
return re.test(email) ? true : "Must be a valid email address"
}
function validCapital(password) {
var recap = new RegExp(/[A-Z]/);
return recap.test(password) ? true : "Password must have a capital letter";
}
function validNumber(password) {
var renum = new RegExp(/\d/);
return renum.test(password) ? true : "Password must have at least one numeric character (0-9)";
}
$(function(){
$("button").click(function(event){
event.preventDefault();
var email = document.forms["sign_up"].elements["email"].value
var password = document.forms["sign_up"].elements["password"].value
var validationsArray = [validEmail(email),
validCapital(password),
validNumber(password),
validPasswordLength(password)]
validationsArray = validationsArray.filter(function(element) {
return element !== true;
})
if (validationsArray.length === 0) {
console.log("All inputs are valid. I would have made the post request, but ...")
}
else {
$.each(validationsArray, function(index, value) {
$('#errors').append("<li>" + value + "</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