renanxusa

Untitled

Oct 27th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.06 KB | None | 0 0
  1. /*
  2. * liquiriziaJs
  3. * http://muvolab.com/demo/liquirizia/
  4. *
  5. * Author Muvolab - Marco Testoni, Samuele Bolognesi, Roberto Serra
  6. */
  7.  
  8. /*
  9. * This file handle the form validation and the ajax calls needed by the contacts form
  10. */
  11.  
  12. // Object containing all the error messages used by the script
  13. var feedback = {
  14. 'required' : 'Campo obrigatório',
  15. 'email' : 'Email inválido',
  16. 'captcha' : 'Conta errada',
  17. 'ok' : 'VALEU!<br> Retornaremos assim que o pombo correio voltar do lanche!',
  18. 'ko' : 'Xii, algo deu errado!'
  19. };
  20.  
  21. // Feedback
  22. var emailSentFeed = '<p class="sent-message">'+feedback.ok+'</p>';
  23. var emailErrorFeed = '<p class="not-sent-message">'+feedback.ko+'</p>';
  24.  
  25. // You can change the html of the feedback
  26. var feedbackHtml = "<small class='js-error-feedback'>{feedback}</small>";
  27. //images ready for the light version, eliminates the previous lines and uncomment the following lines
  28. 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',
  29. 'images/captcha/light/6.png','images/captcha/light/7.png','images/captcha/light/8.png','images/captcha/light/9.png'];
  30.  
  31. var captchaResult = [];
  32.  
  33. /*
  34. * This function extend jQuery for serialize form into objects
  35. */
  36. $.fn.serializeObject = function()
  37. {
  38. var o = {'validateRequired' : [],'validateEmail':[],'validateCaptcha':[]};
  39. var a = this.serializeArray();
  40. $.each(a, function() {
  41. if (o[this.name] !== undefined) {
  42. if (!o[this.name].push) {
  43. o[this.name] = [o[this.name]];
  44. }
  45. o[this.name].push(this.value || '');
  46. } else {
  47. if(typeof $('[name='+this.name+']').attr('data-validate') !== 'undefined'){
  48. var validations = $('[name='+this.name+']').attr('data-validate').split(' ');
  49. if($.inArray('email', validations) >= 0){
  50. o.validateEmail.push(this.name);
  51. }
  52. if($.inArray('required', validations)>= 0){
  53. o.validateRequired.push(this.name);
  54. }
  55. if($.inArray('captcha', validations)>= 0){
  56. o.validateCaptcha.push(this.name);
  57. }
  58. }
  59. o[this.name] = this.value || '';
  60. }
  61. });
  62. return o;
  63. };
  64.  
  65. /*
  66. * This function generate the Captcha using 2 images and the sum
  67. */
  68. function generateCaptcha(){
  69. var val1 = Math.floor(Math.random()*10);
  70. var val2 = Math.floor(Math.random()*10);
  71. captchaResult.push(val1 + val2);
  72. var captchaHtml = $("<span class='js-ca-imgs'></span>");
  73. var img1 = $('<img />');
  74. var img2 = $('<img />');
  75. img1.attr('src',captchaImgs[val1]);
  76. img2.attr('src',captchaImgs[val2]);
  77. captchaHtml.append(img1).append('+').append(img2);
  78. $('.js-ca-imgs').replaceWith(captchaHtml);
  79. }
  80.  
  81. /*
  82. * This function insert the feedback message inside the html
  83. *
  84. * @param f String The feedback name
  85. */
  86. var fetchFeedback = function(f){
  87. var msg = feedback[f];
  88. var str = feedbackHtml;
  89. if(typeof msg !== 'undefined'){
  90. str = str.replace('{feedback}',msg);
  91. return str;
  92.  
  93. } else {
  94. return '';
  95. }
  96. };
  97.  
  98. /*
  99. * This function clear the errors stored inside the form data object
  100. *
  101. * @param data Object The form object
  102. */
  103. function cleanUpData(data){
  104. var pattern = /^validate/;
  105. $.each(data,function(i,n){
  106. if(i.match(pattern) !== null){
  107. delete data[i];
  108. }
  109. });
  110. return data;
  111. }
  112.  
  113. /*
  114. * This function add a error feedback inside the html
  115. *
  116. * @param fName String Name of the input
  117. * @param type String Error type (ex required, email); is optional, calling the function without this param will remove any error feedback
  118. */
  119. function placeErrorMessage(fName, type){
  120. var el = $('[name='+fName+']');
  121. el.addClass('error');
  122. //$('[name='+fName+']').siblings('.js-error-feedback').fadeIn('fast');
  123. f = fetchFeedback(type);
  124. if(!el.siblings('.js-error-feedback').exists()){
  125. if(el.parents('li').hasClass('question')){
  126. el.parents('li').append(f);
  127. } else {
  128. el.before(f);
  129. }
  130. }
  131. }
  132.  
  133. /*
  134. * This function remove the error feedback from the html
  135. *
  136. * @param fName String Name of the input
  137. * @param type String Error type (ex required, email); is optional, calling the function without this param will remove any error feedback
  138. */
  139. function removeErrorMessage(fName, type){
  140. var el = $('[name='+fName+']');
  141. if(typeof type === 'undefined'){
  142. el.removeClass('error');
  143. el.siblings('.js-error-feedback').remove();
  144. } else {
  145. f = fetchFeedback(type);
  146. if(el.siblings('.js-error-feedback').html() == feedback[type]){
  147. el.removeClass('error');
  148. el.siblings('.js-error-feedback').remove();
  149. }
  150. }
  151. }
  152.  
  153. /*
  154. * This function validate a form
  155. *
  156. * @param formData Object The form object returned by
  157. * @return bool Return true if no error were found during the validation
  158. */
  159. function validateForm(formData){
  160. var valid = true;
  161.  
  162. $.each(formData.validateRequired,function(){ // validate required
  163. var fName = this;
  164. var f;
  165. // js validation
  166. if(formData[fName] === ''){
  167. valid = false;
  168. placeErrorMessage(fName,'required');
  169. }
  170. else{
  171. removeErrorMessage(fName,'required');
  172. }
  173. });
  174.  
  175. $.each(formData.validateEmail,function(){
  176. var fName = this;
  177. var str = formData[this];
  178. var pattern = /^[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,4}$/;
  179. var match = str.match(pattern);
  180. if(match === null){
  181. valid = false;
  182. placeErrorMessage(fName,'email');
  183. }
  184. else{
  185. removeErrorMessage(fName,'email');
  186. }
  187. });
  188.  
  189. $.each(formData.validateCaptcha,function(k,v){ // validate required
  190. var fName = this;
  191. // js validation
  192. if(formData[fName] != captchaResult[k]){
  193. valid = false;
  194. placeErrorMessage(fName,'captcha');
  195. }
  196. else{
  197. removeErrorMessage(fName,'captcha');
  198. }
  199. });
  200.  
  201. return valid;
  202. }
  203.  
  204. // when the document is ready let's initialize the mailer
  205. $(document).ready(function($) {
  206. // first we generate the captcha
  207. generateCaptcha();
  208.  
  209. // listener to validate the form on the submit
  210. $('#ajax-mail').on('submit',function(e){
  211. e.preventDefault();
  212. var form = $('#ajax-mail');
  213. var formData = form.serializeObject();
  214. if(validateForm(formData)){
  215. formData = cleanUpData(formData); // remove utility properties from formData
  216. var request = $.ajax({
  217. url: form.attr('action'),
  218. type: "POST",
  219. data: formData,
  220. dataType: "json"
  221. });
  222. request.done(function(obj) {
  223. $.each(formData, function(i,n){ // remove error feedback before set new feedbacks
  224. removeErrorMessage(i);
  225. });
  226. if(obj.result === true){
  227. $('.feedContainerMessage').html(emailSentFeed);
  228. $('#ajax-mail input:not(.send),#ajax-mail textarea').val('');
  229. } else {
  230. $.each(obj.errors, function(i,n){
  231. placeErrorMessage(i,n);
  232. });
  233. $('#ajax-mail').append(emailErrorFeed);
  234. }
  235. });
  236.  
  237. request.fail(function(jqXHR, textStatus) {
  238. $('.feedContainerMessage').html(emailErrorFeed);
  239. });
  240. }
  241. return false;
  242. });
  243.  
  244. // we also want to validate the form, when user change focus
  245. $('#ajax-mail input,#ajax-mail textarea').on('focusout',function(){
  246. var form = $('#ajax-mail');
  247. var formData = $(this).serializeObject();
  248. validateForm(formData);
  249. });
  250.  
  251.  
  252. });
Add Comment
Please, Sign In to add comment