-
-
Save devdame/9257695 to your computer and use it in GitHub Desktop.
Form Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// shorthand for $(document).ready(); | |
$(function(){ | |
//Your code... | |
$("form").on("submit", function(event) { | |
function checkLength(password) { | |
if(password.length < 8) { | |
errors.push("Your password must be at least 8 characters long."); | |
}; | |
}; | |
function checkForCapitals(password) { | |
var regex = /[A-Z]/; | |
if(password.match(regex) === null) { | |
errors.push("Your password must contain at least one capital letter."); | |
}; | |
}; | |
function checkForNumber(password) { | |
var regex = /[1-9]/; | |
if(password.match(regex) === null) { | |
errors.push("Your password must contain at least one number (1-9).") | |
} | |
} | |
function checkEmail(email) { | |
var regex = /(\w|\.)+@(\w|\.)+\.\w{2,}/; | |
if(email.match(regex) === null) { | |
errors.push("You must use a valid email address."); | |
}; | |
}; | |
function appendError(error, index, array) { | |
var ul = document.getElementById("errors"); | |
var newLI = document.createElement("li"); | |
ul.appendChild(newLI); | |
newLI.innerHTML = error | |
} | |
event.preventDefault(); | |
var password = document.forms["sign_up"]["password"].value; | |
var email = document.forms["sign_up"]["email"].value; | |
var errors = []; | |
checkLength(password); | |
checkForCapitals(password); | |
checkForNumber(password); | |
checkEmail(email); | |
errors.forEach(appendError); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ul#errors { | |
color: red; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment