Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * liquiriziaJs
- * http://muvolab.com/demo/liquirizia/
- *
- * Author Muvolab - Marco Testoni, Samuele Bolognesi, Roberto Serra
- */
- /*
- * This file handle the form validation and the ajax calls needed by the contacts form
- */
- // Object containing all the error messages used by the script
- var feedback = {
- 'required' : 'Campo obrigatório',
- 'email' : 'Email inválido',
- 'captcha' : 'Conta errada',
- 'ok' : 'VALEU!<br> Retornaremos assim que o pombo correio voltar do lanche!',
- 'ko' : 'Xii, algo deu errado!'
- };
- // Feedback
- var emailSentFeed = '<p class="sent-message">'+feedback.ok+'</p>';
- var emailErrorFeed = '<p class="not-sent-message">'+feedback.ko+'</p>';
- // You can change the html of the feedback
- var feedbackHtml = "<small class='js-error-feedback'>{feedback}</small>";
- //images ready for the light version, eliminates the previous lines and uncomment the following lines
- var captchaImgs = ['images/captcha/light/0.png','images/captcha/light/1.png','images/captcha/light/2.png','images/captcha/light/3.png','images/captcha/light/4.png','images/captcha/light/5.png',
- 'images/captcha/light/6.png','images/captcha/light/7.png','images/captcha/light/8.png','images/captcha/light/9.png'];
- var captchaResult = [];
- /*
- * This function extend jQuery for serialize form into objects
- */
- $.fn.serializeObject = function()
- {
- var o = {'validateRequired' : [],'validateEmail':[],'validateCaptcha':[]};
- var a = this.serializeArray();
- $.each(a, function() {
- if (o[this.name] !== undefined) {
- if (!o[this.name].push) {
- o[this.name] = [o[this.name]];
- }
- o[this.name].push(this.value || '');
- } else {
- if(typeof $('[name='+this.name+']').attr('data-validate') !== 'undefined'){
- var validations = $('[name='+this.name+']').attr('data-validate').split(' ');
- if($.inArray('email', validations) >= 0){
- o.validateEmail.push(this.name);
- }
- if($.inArray('required', validations)>= 0){
- o.validateRequired.push(this.name);
- }
- if($.inArray('captcha', validations)>= 0){
- o.validateCaptcha.push(this.name);
- }
- }
- o[this.name] = this.value || '';
- }
- });
- return o;
- };
- /*
- * This function generate the Captcha using 2 images and the sum
- */
- function generateCaptcha(){
- var val1 = Math.floor(Math.random()*10);
- var val2 = Math.floor(Math.random()*10);
- captchaResult.push(val1 + val2);
- var captchaHtml = $("<span class='js-ca-imgs'></span>");
- var img1 = $('<img />');
- var img2 = $('<img />');
- img1.attr('src',captchaImgs[val1]);
- img2.attr('src',captchaImgs[val2]);
- captchaHtml.append(img1).append('+').append(img2);
- $('.js-ca-imgs').replaceWith(captchaHtml);
- }
- /*
- * This function insert the feedback message inside the html
- *
- * @param f String The feedback name
- */
- var fetchFeedback = function(f){
- var msg = feedback[f];
- var str = feedbackHtml;
- if(typeof msg !== 'undefined'){
- str = str.replace('{feedback}',msg);
- return str;
- } else {
- return '';
- }
- };
- /*
- * This function clear the errors stored inside the form data object
- *
- * @param data Object The form object
- */
- function cleanUpData(data){
- var pattern = /^validate/;
- $.each(data,function(i,n){
- if(i.match(pattern) !== null){
- delete data[i];
- }
- });
- return data;
- }
- /*
- * This function add a error feedback inside the html
- *
- * @param fName String Name of the input
- * @param type String Error type (ex required, email); is optional, calling the function without this param will remove any error feedback
- */
- function placeErrorMessage(fName, type){
- var el = $('[name='+fName+']');
- el.addClass('error');
- //$('[name='+fName+']').siblings('.js-error-feedback').fadeIn('fast');
- f = fetchFeedback(type);
- if(!el.siblings('.js-error-feedback').exists()){
- if(el.parents('li').hasClass('question')){
- el.parents('li').append(f);
- } else {
- el.before(f);
- }
- }
- }
- /*
- * This function remove the error feedback from the html
- *
- * @param fName String Name of the input
- * @param type String Error type (ex required, email); is optional, calling the function without this param will remove any error feedback
- */
- function removeErrorMessage(fName, type){
- var el = $('[name='+fName+']');
- if(typeof type === 'undefined'){
- el.removeClass('error');
- el.siblings('.js-error-feedback').remove();
- } else {
- f = fetchFeedback(type);
- if(el.siblings('.js-error-feedback').html() == feedback[type]){
- el.removeClass('error');
- el.siblings('.js-error-feedback').remove();
- }
- }
- }
- /*
- * This function validate a form
- *
- * @param formData Object The form object returned by
- * @return bool Return true if no error were found during the validation
- */
- function validateForm(formData){
- var valid = true;
- $.each(formData.validateRequired,function(){ // validate required
- var fName = this;
- var f;
- // js validation
- if(formData[fName] === ''){
- valid = false;
- placeErrorMessage(fName,'required');
- }
- else{
- removeErrorMessage(fName,'required');
- }
- });
- $.each(formData.validateEmail,function(){
- var fName = this;
- var str = formData[this];
- var pattern = /^[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,4}$/;
- var match = str.match(pattern);
- if(match === null){
- valid = false;
- placeErrorMessage(fName,'email');
- }
- else{
- removeErrorMessage(fName,'email');
- }
- });
- $.each(formData.validateCaptcha,function(k,v){ // validate required
- var fName = this;
- // js validation
- if(formData[fName] != captchaResult[k]){
- valid = false;
- placeErrorMessage(fName,'captcha');
- }
- else{
- removeErrorMessage(fName,'captcha');
- }
- });
- return valid;
- }
- // when the document is ready let's initialize the mailer
- $(document).ready(function($) {
- // first we generate the captcha
- generateCaptcha();
- // listener to validate the form on the submit
- $('#ajax-mail').on('submit',function(e){
- e.preventDefault();
- var form = $('#ajax-mail');
- var formData = form.serializeObject();
- if(validateForm(formData)){
- formData = cleanUpData(formData); // remove utility properties from formData
- var request = $.ajax({
- url: form.attr('action'),
- type: "POST",
- data: formData,
- dataType: "json"
- });
- request.done(function(obj) {
- $.each(formData, function(i,n){ // remove error feedback before set new feedbacks
- removeErrorMessage(i);
- });
- if(obj.result === true){
- $('.feedContainerMessage').html(emailSentFeed);
- $('#ajax-mail input:not(.send),#ajax-mail textarea').val('');
- } else {
- $.each(obj.errors, function(i,n){
- placeErrorMessage(i,n);
- });
- $('#ajax-mail').append(emailErrorFeed);
- }
- });
- request.fail(function(jqXHR, textStatus) {
- $('.feedContainerMessage').html(emailErrorFeed);
- });
- }
- return false;
- });
- // we also want to validate the form, when user change focus
- $('#ajax-mail input,#ajax-mail textarea').on('focusout',function(){
- var form = $('#ajax-mail');
- var formData = $(this).serializeObject();
- validateForm(formData);
- });
- });
Add Comment
Please, Sign In to add comment