Last active
December 25, 2015 19:49
-
-
Save ukutaht/7030702 to your computer and use it in GitHub Desktop.
Javascript form validation
This file contains hidden or 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
$(document).ready(function(){ | |
$(document).on("submit","form", function(event){ | |
event.preventDefault(); | |
var email = $("form").find("#email").val(); | |
var password = $("form").find("#password").val(); | |
var errors = checkEmailErrors(email).concat(checkPasswordErrors(password)); | |
if (errors.length === 0){ | |
$("#errors").html("success"); | |
}else{ | |
var displayErrors = "<ul style='color:red'>" | |
for(i in errors){ | |
displayErrors = displayErrors + "<li>" + errors[i] + "</li>" | |
} | |
displayErrors = displayErrors + "</ul>" | |
$("#errors").html(displayErrors); | |
} | |
}) | |
}) | |
function checkEmailErrors(email){ | |
var emailRegex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; | |
var emailErrors = [] | |
if (!email.match(emailRegex)){ | |
emailErrors.push("Invalid email") | |
} | |
return emailErrors | |
} | |
function checkPasswordErrors(password){ | |
var passwordErrors = [] | |
if(password.length < 8){ | |
passwordErrors.push("Password must be longer than 8 characters") | |
} | |
if(!password.match(/[a-z]+/)){ | |
passwordErrors.push("Password must contain at least one lowercase character") | |
} | |
if(!password.match(/[A-Z]+/)){ | |
passwordErrors.push("Password must contain at least one uppercase character") | |
} | |
return passwordErrors | |
} |
This file contains hidden or 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"> | |
<title>Form Validations</title> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> | |
<script src="app.js"/></script> | |
</head> | |
<body> | |
<form action="/watever" method="post"/> | |
<input id="email" type="text"/> | |
<input id="password" type="password"/> | |
<br> | |
<input type="submit" value="Click me!"/> | |
</form> | |
<div id="errors"> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment