Skip to content

Instantly share code, notes, and snippets.

@burke187
Forked from ksolo/form-validator.js
Last active December 25, 2015 19:49
Form Validation
function Validator() {
this.errors = [];
this.valid = true
};
Validator.prototype.eval = function(input,format,message) {
if (input.match(format) == nil){
this.errors.push(message);
this.valid = false;
}
}
Validator.prototype.checkEmail = function(email){
var format = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
var message = "Must be a valid email address, dawg!"
this.eval(email,format,message);
};
Validator.prototype.checkPasswordNums = function(password){
var format = /\d/;
var message = "Password must contain at least one number"
this.eval(password,format,message);
};
Validator.prototype.checkPasswordCaps = function(password){
var format = /\[A-Z]/;
var message = "Password must have at least one capital letter"
this.eval(password,format,message);
};
Validator.prototype.checkPasswordLength = function(password){
if (password.length < 8 == true){
this.errors.push(message);
this.valid = false;
};
};
Validator.prototype.validate = function(email, password){
this.checkEmail(email);
this.checkPasswordNums(password);
this.checkPasswordCaps(password);
this.checkPasswordLength(password);
};
Validator.prototype.show_errors = function(){
$.each(this.errors, function(index, value){
$('#errors').append("<li>" + value + "</li>");
});
validator.valid = true;
validator.errors = [];
}
$(function(){
validator = new Validator();
$('form').on('submit', funtion(event){
event.preventDefault();
$('#errors').empty();
var email = $(':input[type="text"]').val();
var password = $(':input[type="password"]').val();
validator.validate(email, password);
if (validator.valid == false) {
validator.show_errors();
} else {
$(this).unbind('submit').submit();
};
});
});
<!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