Skip to content

Instantly share code, notes, and snippets.

@Daniel-Griffiths
Last active July 13, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel-Griffiths/de25dd71f85e9be230faf56c7d5c4274 to your computer and use it in GitHub Desktop.
Save Daniel-Griffiths/de25dd71f85e9be230faf56c7d5c4274 to your computer and use it in GitHub Desktop.
Form Validater
/*
* Plugin: Validate v0.1
* Author: Daniel Griffiths
*/
(function($) {
$.fn.validate = function(){
this.each(function(){
var form = this;
$(form).on('submit',function(e){
e.preventDefault();
/* reset the errors */
$('.validation-error').remove();
/* get all the required inputs of the form */
$(form).find('input[required],select[required],textarea[required]').each(function(){
$(this).on('click',function(){
/* reset the errors */
$('.validation-error').remove();
});
validateInput($(this),$(this).attr('type'));
});
});
function validateInput(element,type){
var offset = element.offset();
var message = 'Error';
var error = false;
/* check for a valid email */
if(type == 'email' && validateEmail(element.val()) == false){
message = 'Please enter a valid email';
error = true;
}
/* check for a valid email */
if(type == 'tel' && validateTelephone(element.val()) == false){
message = 'Please enter a valid telephone number';
error = true;
}
/* check if the element is empty */
if(element.val() == ''){
message = 'Please fill this field';
error = true;
}
/* add warning message */
if(error == true){
$('<div class="validation-error" style="top:'+offset['top']+';left:'+offset['left']+';">'+ message +'</div>').insertBefore(element);
/* scroll user to the input */
$('html, body').animate({
scrollTop: $('.validation-error').offset().top
}, 100);
return false;
}
return true;
}
function validateEmail(email) {
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,}))$/;
return re.test(email);
}
function validateTelephone(number) {
}
/* add styles to the body */
$('body').append(''+
'<style>'+
'.validation-error{'+
'font-family: arial;transform:translateY(-100%);-webkit-transform:translateY(-100%);background: #B34242;padding: 5px 12px;font-size: 12px;color: #fff;position:absolute;'+
'}'+
'.validation-error:after{' +
'top: 99%;left: 0; border: solid transparent;content: " ";height: 0;width: 0;position: absolute;pointer-events: none;border-color: rgba(204,49,49,0);border-top-color: #B34242;border-width: 6px;margin-left: 10px;' +
'}' +
'</style>');
});
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment