Skip to content

Instantly share code, notes, and snippets.

@shidel-dev
Forked from ksolo/form-validator.js
Last active August 29, 2015 13:56
Show Gist options
  • Save shidel-dev/8851231 to your computer and use it in GitHub Desktop.
Save shidel-dev/8851231 to your computer and use it in GitHub Desktop.
Form Validation
$(function() {
$("form[name='sign_up']").submit(function(event) {
event.preventDefault();
$("#errors").empty()
var email = validateEmail($("input[name='email']"));
var password = validatePassword($("input[name='password']"));
if (email == true) {
if (password == true) {
$("#errors").append("<ui>Success</ui>");
} else {
for (var i = 0; i < password.length; i++) {
$("#errors").append(password[i])
}
}
} else {
$("#errors").append(email)
}
})
});
function validateEmail(elem) {
if ((/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i).test(elem.val())) {
return true
} else {
return "<ui>Must be a valid Email</ui>"
}
}
function validatePassword(elem) {
var messages = [];
var str = elem.val();
if (/.{8,}/.test(str) == false) {
messages.push("<ui>password must be at least 8 in length</ui><br>");
};
if (/[A-Z]+/.test(str) == false) {
messages.push("<ui>password must be at least one upcase letter</ui><br>");
};
if (/[0-9]+/.test(str) == false) {
messages.push("<ui>password must be at least one number</ui><br>");
};
if (messages == []) {
return true
} else {
return messages
}
}
//\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
<!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