Skip to content

Instantly share code, notes, and snippets.

@Carpk
Forked from ksolo/form-validator.js
Last active December 27, 2015 16:59
Show Gist options
  • Select an option

  • Save Carpk/7358987 to your computer and use it in GitHub Desktop.

Select an option

Save Carpk/7358987 to your computer and use it in GitHub Desktop.
Form Validation
// shorthand for $(document).ready();
$(function(){
$("form").on("click", function(event) {
event.preventDefault();
var email = document.forms["sign_up"]["email"].value;
var password = document.forms["sign_up"]["password"].value;
console.log(email.match(/\b[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}\b/))
if (email.match(/\b[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}\b/) === null) {
console.log("email did not match")
return
}
if (password.match(/[[a-z]+[A-Z]+[0-9]+]{8,}/) === null ){
console.log("password did not match")
return
}
console.log("you win! yay!")
})
});
// When the user clicks the "Sign Up" button
// They should be notified if any of the following conditions are NOT true
// - The email conforms to the standard pattern
// - The password has at least 8 characters
// - The password has at least one capital letter
// - The password has at least one numeric character
// If any of the above conditions are false
// - The form is not allowed to be submitted
// - Error messages are dislpayed
<!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