Skip to content

Instantly share code, notes, and snippets.

@Gix075
Last active April 28, 2020 18:19
Show Gist options
  • Save Gix075/276fd4399691c2388a0e to your computer and use it in GitHub Desktop.
Save Gix075/276fd4399691c2388a0e to your computer and use it in GitHub Desktop.
Form Validation
/*
Form Validator 2.1.1 by Gix075
===================================================================
This is an useful class that you can use to validate any forms.
*/
function formValidator(globOpts) {
var defaults = {
bootstrap: true,
mail: {
format: true,
confirm: true
},
password: {
format: true,
formatRegEx: /\b([A-Z0-9])([a-z0-9]+)?\b/gm,
confirm: true
},
telephone: {
numbersOnly: false
},
showErrors: true
},
opts = $.extend( true, defaults, globOpts ),
validator = this;
this.opts = opts,
this.formValidation = true,
this.validInput = false,
this.validTextarea = false,
this.validPassword = false,
this.validEmail = false,
this.validSelect = false,
this.validRadio = false,
this.validCheckbox = false,
this.validPhone = false,
// validation method
this.validate = function(element, button, callbacks) {
$(button).on('click', function(e) {
e.preventDefault();
var form = $('form' + element),
input = form.find('input.validate').not('input[type="radio"]').not('input[type="checkbox"]'),
password = form.find('input[type="password"].validate'),
phone = form.find('input[type="tel"].validate'),
textarea = form.find('textarea.validate'),
select = form.find('select.validate'),
email = form.find('input[type="email"].validate'),
radio = form.find('.radio-group.validate'),
checkbox = form.find('.checkbox-group.validate'),
loopError = 0;
// text, tel and all commons inputs
// ****************************************************
$(input).each(function() {
if ($(this).val() == "") {
if (opts.showErrors === true) validator.showError(this, 'input', 'empty');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'input');
}
});
validator.validInput = (loopError > 0) ? false : true;
loopError = 0;
// end input
// telephone input
// ****************************************************
if (opts.telephone.numbersOnly === true) {
$(phone).each(function() {
var telValue = $(this).val();
if (telValue != "") {
var reg = /^\d+$/;
if (reg.test(telValue) === false) {
if (opts.showErrors === true) validator.showError(this, 'input', 'wrong');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'input');
}
}
});
}
validator.validPhone = (loopError > 0) ? false : true;
loopError = 0;
// end telephone
// textarea
// ****************************************************
$(textarea).each(function() {
if ($(this).val() == "") {
if (opts.showErrors === true) validator.showError(this, 'textarea', 'empty');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'textarea');
}
});
validator.validTextarea = (loopError > 0) ? false : true;
loopError = 0;
// end textarea
// select
// ****************************************************
$(select).each(function() {
if (!$("option:selected", this).not('.not-option').length) {
if (opts.showErrors === true) validator.showError(this, 'select', 'empty');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'select');
}
});
validator.validSelect = (loopError > 0) ? false : true;
loopError = 0;
// end select
// email
// ****************************************************
$(email).not('.email-confirm').each(function() {
if ($(this).val() != "" && opts.mail.format === true) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test($(this).val()) === false) {
if (opts.showErrors === true) validator.showError(this, 'email', 'wrong');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'email');
}
}
if ($(this).val() != "" && opts.mail.confirm === true && loopError == 0) {
console.log($(this).attr('id'));
var confirmElement = $('.email-confirm[data-confirm="#' + $(this).attr('id') + '"]');
if ($(this).val() != $(confirmElement).val()) {
if (opts.showErrors === true) validator.showError(confirmElement, 'email', 'wrong');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(confirmElement, 'email');
}
}
});
validator.validEmail = (loopError > 0) ? false : true;
loopError = 0;
// end email
// password
// ****************************************************
//password format
if (opts.password.format === true) {
$(password).not('.pswd-confirm').each(function() {
if ($(this).val() != "") {
var string = $(this).val(),
regex = opts.password.formatRegEx;
if (string.match(regex)) {
if (opts.showErrors === true) validator.hideError(this, 'password');
} else {
if (opts.showErrors === true) validator.showError(this, 'password', 'wrong');
loopError = loopError + 1;
}
}
});
}
// password confirm
if (opts.password.confirm === true) {
$('.pswd-confirm').each(function() {
if ($(this).val() != "") {
var confirmPswdElement = $(this).data('confirm');
if ($(this).val() != $(confirmPswdElement).val()) {
if (opts.showErrors === true) validator.showError(this, 'password', 'wrong');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'password');
}
}
});
}
validator.validPassword = (loopError > 0) ? false : true;
loopError = 0;
// end password
// radio
// ****************************************************
$(radio).each(function() {
var checkedbox = false;
$(this).find('input[type="radio"]').each(function() {
if ($(this).is(':checked')) checkedbox = true;
})
if (checkedbox === false) {
if (opts.showErrors === true) validator.showError(this, 'radio', 'empty');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'radio');
}
});
validator.validRadio = (loopError > 0) ? false : true;
loopError = 0;
// end radio
// checkbox
// ****************************************************
$(checkbox).each(function() {
var checkedbox = false;
$(this).find('input[type="checkbox"]').each(function() {
if ($(this).is(':checked')) checkedbox = true;
})
if (checkedbox === false) {
if (opts.showErrors === true) validator.showError(this, 'checkbox', 'empty');
loopError = loopError + 1;
} else {
if (opts.showErrors === true) validator.hideError(this, 'checkbox');
}
});
validator.validCheckbox = (loopError > 0) ? false : true;
loopError = 0;
// end checkbox
// Callback Functions
// ****************************************************
if (validator.validInput === true && validator.validPassword === true && validator.validPhone === true && validator.validTextarea === true && validator.validEmail === true && validator.validSelect === true && validator.validRadio === true && validator.validCheckbox === true) {
callbacks.success();
} else {
callbacks.fail();
}
}); //end click
}, // end validate()
this.showError = function(inputElement, inputType, errorType) {
if (inputType == 'radio' || inputType == 'checkbox') {
// checkbox and radio error message
(opts.bootstrap === true) ? $(inputElement).closest('.' + inputType + '-group').addClass('has-error'): $(inputElement).addClass('error');
$(inputElement).closest('.' + inputType + '-group').find('.form-input-error-msg').addClass('show-error');
} else {
// common inputs error message
(opts.bootstrap === true) ? $(inputElement).closest('.form-group').addClass('has-error'): $(inputElement).addClass('error');
$(inputElement).prev('.form-input-error-msg').addClass('show-error');
switch (errorType) {
case 'empty':
$(inputElement).prev('.form-input-error-msg').find('.error-wrong').removeClass('show-error');
$(inputElement).prev('.form-input-error-msg').find('.error-empty').addClass('show-error');
break;
case 'wrong':
$(inputElement).prev('.form-input-error-msg').find('.error-empty').removeClass('show-error');
$(inputElement).prev('.form-input-error-msg').find('.error-wrong').addClass('show-error');
break;
} //end switch
}
},
this.hideError = function(inputElement, inputType) {
if (inputType == 'radio' || inputType == 'checkbox') {
(opts.bootstrap === true) ? $(inputElement).closest('.' + inputType + '-group').removeClass('has-error'): $(inputElement).removeClass('error');
$(inputElement).closest('.' + inputType + '-group').find('.form-input-error-msg').removeClass('show-error');
} else {
(opts.bootstrap === true) ? $(inputElement).closest('.form-group').removeClass('has-error'): $(inputElement).removeClass('error');
$(inputElement).prev('.form-input-error-msg').removeClass('show-error');
$(inputElement).prev('.form-input-error-msg').find('.error-empty,.error-wrong').removeClass('show-error');
}
},
this.clearError = function(formElement) {
$(formElement).find('*').removeClass('error');
$(formElement).find('*').removeClass('has-error');
$(formElement).find('*').removeClass('show-error');
}
}
<!-- Require Bootstrap and formValidator.js -->
<!DOCTYPE HTML>
<html>
<head>
<title>Form Validator Demo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="formValidator_style.css">
</head>
<body>
<form id="form">
<h3>Bootstrap formValidator <small>version 2.1.1</small></h3>
<p>This is a simple demo of a form validation jquery class</p>
<!-- Text Inputs -->
<!-- ==================================================================== -->
<hr>
<h4>TEXT INPUTS</h4>
<div class="form-group">
<label class="control-label" for="input_1">Text 1</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> This field is mandatary</div>
<input type="text" id="input_1" class="form-control validate">
</div>
<div class="form-group">
<label class="control-label" for="input_2">Text 2</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> Error Message</div>
<input type="text" id="input_2" class="form-control validate">
</div>
<!-- Email -->
<!-- ==================================================================== -->
<hr>
<h4>EMAIL INPUTS</h4>
<div class="form-group">
<label class="control-label" for="email">Email</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> <span class="error-empty">Empty Field</span>
<span class="error-wrong">Mail not correct</span>
</div>
<input type="email" id="email" class="form-control validate email-format">
</div>
<div class="form-group">
<label class="control-label" for="emailConfirm">Email Confirm</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> <span class="error-empty">Empty Field</span>
<span class="error-wrong">Mail not confirmed</span>
</div>
<input type="email" id="emailConfirm" class="form-control validate email-confirm" data-confirm="#email">
</div>
<!-- Password -->
<!-- ==================================================================== -->
<hr>
<h4>PASSWORD INPUTS</h4>
<div class="form-group">
<label class="control-label" for="password">Password</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> Type your password
</div>
<input type="password" id="password" class="form-control validate pswd">
</div>
<div class="form-group">
<label class="control-label" for="passwordConfirm">Confirm Password</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span>
<span class="error-empty">Confirm your password</span>
<span class="error-wrong">Passwords don't match</span>
</div>
<input type="password" id="passwordConfirm" class="form-control validate pswd-confirm" data-confirm="#password">
</div>
<!-- Phone Inputs -->
<!-- ==================================================================== -->
<hr>
<h4>PHONE INPUTS</h4>
<div class="form-group">
<label class="control-label" for="phone">Telephone Number</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span>
<span class="error-empty"> Insert your Phone Number</span>
<span class="error-wrong" >Not correct number</span>
</div>
<input type="tel" id="phone" class="form-control validate">
</div>
<!-- Selects -->
<!-- ==================================================================== -->
<hr>
<h4>SELECT</h4>
<div class="form-group">
<label class="control-label" for="select_1">Select</label>
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> Select an option
</div>
<select id="select_1" class="validate form-control">
<option class="not-option">Select an Option</option>
<option val="1">Option 1</option>
<option val="2">Option 2</option>
<option val="3">Option 3</option>
</select>
</div>
<!-- Radios -->
<!-- ==================================================================== -->
<hr>
<h4>RADIO</h4>
<div class="form-group radio-group validate">
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> Select an option
</div>
<div class="radio">
<label class="control-label">
<input type="radio" value="1" name="radio_1"> Option 1
</label>
</div>
<div class="radio">
<label class="control-label">
<input type="radio" value="2" name="radio_1"> Option 2
</label>
</div>
</div><!-- /.radio-group -->
<!-- Checkboxes -->
<!-- ==================================================================== -->
<hr>
<h4>CHECKBOX</h4>
<div class="form-group checkbox-group validate">
<div class="form-input-error-msg alert alert-danger">
<span class="glyphicon glyphicon-exclamation-sign"></span> Select an option
</div>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" value="1" name="checkbox_1"> Option 1
</label>
</div>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" value="2" name="checkbox_1"> Option 2
</label>
</div>
</div><!-- /.checkbox-group -->
<!-- Textarea -->
<!-- ==================================================================== -->
<hr>
<h4>TEXTAREA</h4>
<div class="form-group">
<label class="control-label" for="textarea_1">TextArea</label>
<div class="form-input-error-msg alert alert-danger"><span class="glyphicon glyphicon-exclamation-sign"></span> Insert some text
</div>
<textarea id="textarea_1" class="form-control validate"></textarea>
</div>
<button id="submit">Sumbit</button>
</form>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="formValidator.js"></script>
<!-- Javascript -->
<script>
$(document).ready(function() {
var globOpts = {
bootstrap: true,
mail: {
format: true,
confirm: true
},
password: {
format: true,
formatRegEx: /\b([A-Z0-9])([a-z0-9]+)?\b/gm,
confirm: true
},
telephone: {
numbersOnly: false
},
showErrors: true
}
var fv = new formValidator(globOpts)
var validation = fv.validate('#form', '#submit', {
success: function() {
alert('validation success!')
},
fail: function() {
alert('validation fail!')
}
});
});
</script>
</body>
</html>
/* ======================== */
/* FORM VALIDATOR CSS STYLE */
/* ======================== */
.form-input-error-msg {
display: none;
padding: 4px 0;
margin-bottom: 5px;
color: red;
font-weight: bold;
font-size: 0.8em;
overflow: hidden;
}
.form-input-error-msg.show-error {
display: block;
}
.alert.form-input-error-msg {
padding: 4px;
margin-bottom: 5px;
color: #a94442;
font-weight: bold;
}
.form-input-error-msg span.error-empty,
.form-input-error-msg span.error-wrong {
display: none;
}
.form-input-error-msg span.error-empty.show-error,
.form-input-error-msg span.error-wrong.show-error {
display: inline-block;
}
.error {
border-color: red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment