danjapro Posted August 25, 2014 Share Posted August 25, 2014 We are not getting the error message, that should match with the error_code We sending the code and the object contains the error/success message to show!!! This seems to almost works. It is part of Jquery Validations, once the field or submit button is clicked. It looks for error on field. then Enter the Ajax Funciton which is to parse the error code and the out put the error message which is coming from json object. The code is not returning the error message, on line (alert(data)) Produces [object,object] not actual data string. The error message does not return. Please help, is there something work with our ajax request //*new style for error Messages*/ //var jsonErrors = frontEndErrorCodes; //JC wrote. //MG added. To retrieve Front-end error codes as well as //Backend Error Codes function _getErrorMessage(errorCode, message){ var errorData = JSON.stringify({error_code: errorCode, message: message}); var dataString = $.parseJSON(errorData); $.ajax({ url: './retrieveErrorMessage.json', type: 'POST', data: dataString, dataType: "json", contentType: 'application/json', mimeType: 'application/json', success: function(data) { //data = $.parseJSON(data); alert(data); $('.error.message').contents().find('h4').text(data.message); // if(!vanillaeGift.notify.called) { // $('.error.message').contents().find('h4').text(error.text()); // vanillaeGift.notify.showNotification(".error"); // } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice ==true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, error: function(data) { //data = $.parseJSON(data); alert(data); $('.error.message').contents().find('h4').text(data.message); // if(!vanillaeGift.notify.called) { // $('.error.message').contents().find('h4').text(error.text()); // vanillaeGift.notify.showNotification(".error"); // } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice == true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, fail: function(jqXHR, textStatus) { alert(data); if(textStatus == "parsererror"){ return "We're Sorry a system error occured"; } } }); } Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/ Share on other sites More sharing options...
CroNiX Posted August 25, 2014 Share Posted August 25, 2014 Yes, you can't 'alert' an object. Use the browser's js console, or firebugs, to see the object and be able to traverse it. instead of alert(data); use console.log(data); Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488876 Share on other sites More sharing options...
danjapro Posted August 25, 2014 Author Share Posted August 25, 2014 We got the entire response back. - console Log What we need from the response is whats in the respsonText. how would we look at only the responseText and get the value that mathces the key error_code == data.responseText.message?? "[ { "title": "Vanilla Reoad EN US Generic Messages", "url_title": "vanilla_reload-en-us-gen-messages", "entry_id": 61, "expiration_date": null, "error_messages_m": [ { "row_id": 236, "server_code": "code.ws.invalidCardNumber", "error_code": "-1", "message": "Invalid Details Code 111" }, { "row_id": 237, "server_code": "code.ws.invalidCVV", "error_code": "-1", "message": "Invalid Details Code 222" }, { "row_id": 240, "server_code": "code.ws.invalidInformation", "error_code": "-1", "message": "Invalid Details Code 333" }, { "row_id": 248, "server_code": "code.ws.invalidPinNumber", "error_code": "-1", "message": "Invalid PIN Number" }, { "row_id": 249, "server_code": "code.ws.invalidConfirmNumber", "error_code": "-1", "message": "Invalid Confirmation Number" }, { "row_id": 250, "server_code": "code.ws.invalidZipcode", "error_code": "-1", "message": "Invalid US Zipcode" }, { "row_id": 001, "server_code": "code.fe.InvalidData", "error_code": "001", "message": "Please enter a valid Info" }, { "row_id": 002, "server_code": "code.fe.InvalidSelect", "error_code": "002", "message": "Please select valid choice" }, { "row_id": 254, "server_code": "code.fe.InvalidPinNumber", "error_code": "100", "message": "Please enter a valid Log In ID" }, { "row_id": 255, "server_code": "code.fe.invalidConfirmNumber", "error_code": "101", "message": "Please enter a valid Confirmation Number" }, { "row_id": 241, "server_code": "code.fe.invalidCardNumber", "error_code": "110", "message": "Invalid Card Number" }, { "row_id": 242, "server_code": "code.fe.invalidCVV", "error_code": "111", "message": "Invalid CVV" }, { "row_id": 253, "server_code": "code.fe.invalidExp", "error_code": "112", "message": "Invalid Expiration Date" }, { "row_id": 257, "server_code": "code.fe.invalidZipcode", "error_code": "120", "message": "Please enter a valid ZIP Code" }, { "row_id": 256, "server_code": "code.fe.invalidScoopEmail", "error_code": "200", "message": "Please enter a valid Email address" } ], "success_messages_m": [ { "row_id": 238, "form": "azpc", "message": "You have successfully assign a Zipcode to your Account" }, { "row_id": 239, "form": "news", "message": "You have successfully signed up for our Newsletter" }, { "row_id": 243, "form": "mpin", "message": "Your Account gift Card PIN has been Cleared!" } ] }]" Please advise Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488918 Share on other sites More sharing options...
CroNiX Posted August 25, 2014 Share Posted August 25, 2014 What do you mean "responseText"? I don't see that in that json object. Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488919 Share on other sites More sharing options...
danjapro Posted August 25, 2014 Author Share Posted August 25, 2014 What do you mean "responseText"? I don't see that in that json object. It is part of the json pbj, from the response. Where are the KEY :VALUE pairs are written. In console.log Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488923 Share on other sites More sharing options...
CroNiX Posted August 25, 2014 Share Posted August 25, 2014 That isn't a well formed json object. I can't parse it with php or jquery. It causes errors, so this is probably why you're having problems. Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488925 Share on other sites More sharing options...
CroNiX Posted August 25, 2014 Share Posted August 25, 2014 Try removing the outermost brackets (one [ at beginning and one ] at end) Then you should be able to access: data.entry_id data.expiration_date data.title data.url_title data.error_messages_m (array of objects) data.success_messages_m (array of objects) Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488927 Share on other sites More sharing options...
danjapro Posted August 26, 2014 Author Share Posted August 26, 2014 I fixed the json Object, there were couple issues with the structure. [ { "title": "Vanilla Reoad EN US Generic Messages", "url_title": "vanilla_reload-en-us-gen-messages", "entry_id": 61, "expiration_date": null, "error_messages_m": [ { "row_id": 236, "server_code": "code.ws.invalidCardNumber", "error_code": "-1", "message": "Invalid Details Code 111" }, { "row_id": 237, "server_code": "code.ws.invalidCVV", "error_code": "-1", "message": "Invalid Details Code 222" }, { "row_id": 240, "server_code": "code.ws.invalidInformation", "error_code": "-1", "message": "Invalid Details Code 333" }, { "row_id": 248, "server_code": "code.ws.invalidPinNumber", "error_code": "-1", "message": "Invalid PIN Number" }, { "row_id": 249, "server_code": "code.ws.invalidConfirmNumber", "error_code": "-1", "message": "Invalid Confirmation Number" }, { "row_id": 250, "server_code": "code.ws.invalidZipcode", "error_code": "-1", "message": "Invalid US Zipcode" }, { "row_id": 100, "server_code": "code.fe.InvalidData", "error_code": "001", "message": "Please enter a valid Info" }, { "row_id": 200, "server_code": "code.fe.InvalidSelect", "error_code": "002", "message": "Please select valid choice" }, { "row_id": 254, "server_code": "code.fe.InvalidPinNumber", "error_code": "100", "message": "Please enter a valid Log In ID" }, { "row_id": 255, "server_code": "code.fe.invalidConfirmNumber", "error_code": "101", "message": "Please enter a valid Confirmation Number" }, { "row_id": 241, "server_code": "code.fe.invalidCardNumber", "error_code": "110", "message": "Invalid Card Number" }, { "row_id": 242, "server_code": "code.fe.invalidCVV", "error_code": "111", "message": "Invalid CVV" }, { "row_id": 253, "server_code": "code.fe.invalidExp", "error_code": "112", "message": "Invalid Expiration Date" }, { "row_id": 257, "server_code": "code.fe.invalidZipcode", "error_code": "120", "message": "Please enter a valid ZIP Code" }, { "row_id": 256, "server_code": "code.fe.invalidScoopEmail", "error_code": "200", "message": "Please enter a valid Email address" } ], "success_messages_m": [ { "row_id": 238, "form": "azpc", "message": "You have successfully assign a Zipcode to your Account" }, { "row_id": 239, "form": "news", "message": "You have successfully signed up for our Newsletter" }, { "row_id": 243, "form": "mpin", "message": "Your Account gift Card PIN has been Cleared!" } ] } ] CroNix, We will try and get back to you on that.. thank you for testing and finding possible issue. Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488953 Share on other sites More sharing options...
CroNiX Posted August 26, 2014 Share Posted August 26, 2014 Once I removed the outer most open/close brackets, php json_decode() worked and also jQuery (not going through php) could read it as an object. Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488956 Share on other sites More sharing options...
danjapro Posted August 26, 2014 Author Share Posted August 26, 2014 CroNix, We are able to get there error_message into a loop in jquery as each statemement. And doing error code compare, but it only produces the last error message from the error_messages_m, array. Why is it not stop and taking the error that matches by errorCode == error_code. //*new style for error Messages*/ //var jsonErrors = frontEndErrorCodes; //JC wrote. //MG added. To retrieve Front-end error codes as well as //Backend Error Codes function _getErrorMessage(errorCode, message){ var errorData = JSON.stringify({error_code: errorCode, message: message}); var dataString = $.parseJSON(errorData); $.ajax({ url: './retrieveErrorMessage.json', type: 'POST', data: dataString, dataType: "json", contentType: 'application/json', mimeType: 'application/json', success: function(data) { //data = $.parseJSON(data); // console.log(data); // console.log(errorCode); // console.log(data.error_messages_m); $.each(data.error_messages_m, function(error_code, message ) { if(errorCode == message.error_code && errorCode != -1 ){ console.log(errorCode + message.error_code); console.log(message.message); return false; } var message = message.message; //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice ==true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }); }, error: function(data) { //data = $.parseJSON(data); console.log(data); console.log(errorCode); console.log(data.message); //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.error_messages_m); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice == true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, fail: function(jqXHR, textStatus) { alert(data); if(textStatus == "parsererror"){ return "We're Sorry a system error occured"; } } }); } Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488995 Share on other sites More sharing options...
CroNiX Posted August 26, 2014 Share Posted August 26, 2014 Several things. First and foremost, don't you use the js console in your browser? It shows these errors, like "ReferenceError: errorCode is not defined". In the $.each parameters you pass to the function, you define as error_code but in your check you check for errorCode, which doesn't exist like the error says. Where you are using errorCode in the $each loop, it is actually the array index of message. It works like: $.each(object, function(index, data){}); So that line should be if(message.error_code != -1 ){ Also, in that loop, you return false which will prevent anything else from executing in the loop. Maybe you just have that there for testing? Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1488999 Share on other sites More sharing options...
danjapro Posted August 27, 2014 Author Share Posted August 27, 2014 Cronix, It seems to almost works, but the error message it shows no error message.Its seems to be going thru the loop and then when completed, it take the message as nothing. I cannot figure this out..If I comment that out, then it captures the last error message "Please enter valid e-mail address".I cannot seem to get this thing to work man.. I really need your help.. Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1489090 Share on other sites More sharing options...
CroNiX Posted August 27, 2014 Share Posted August 27, 2014 post your current code Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1489095 Share on other sites More sharing options...
danjapro Posted August 27, 2014 Author Share Posted August 27, 2014 Cronix, got another issue need some help with too: Both issues: Error message are not coming back as needed, geting last error message only for each field validation error. & Also, another issue here once you enter into the _getErrorMessage function,It wil not allow you to submit the form. I think I need some help with that to. Can you please test locally on your PC and get it working Need:Get correct error messageSubmit form once fields are good and no errors Attached my entire validations.js file, take look and let me know. what we doing wrong here. Copy entire file and then you can paste into text editor and see complete flow. // JavaScript Document// Pop-up notification // Multiple Notification can be set here also // Change both to 1 and then they are enabled // See Lines (), for the functionality // MG. Added feature 07/2014 var BoltNotify = true; var multipleNotice = false; var validatejson = { formats: { //email: /^\w+@[^\s\.]+\.[^\s\.]+[^\s]*[^\s\.]*$/, name: /^[a-zA-Z ]*$/, email: /^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/, ip: /^(\d{1,3}\.){3}\d{1,3}$/, date: /^\d{2}[- \/.]\d{2}[- \/.]\d{4}$/, /* ^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$ */ datetime: /^\d{2}[- \/.]\d{2}[- \/.]\d{4}\s?\d{2}[- :.]\d{2}$/, phone: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/, //phone: /^[0-9]*$/, zipUS: /^(\d{5})(-\d{4})?$/, /* /^([0-9]{5})(?:[-\s]([0-9]{4}))?$/; */ zipCanada: /^[a-z][0-9][a-z]\s?[0-9][a-z][0-9]$/i,/* /^([A-Z][0-9][A-Z])\s([0-9][A-Z][0-9])$/; */ zip: /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+))?$/, creditCard: /^\d{13,16}$/, numeric: /^\d+$/, /* [0-9]+ */ number: /^\d+$/, cvvnum: /^\d+$/, /* [0-9]+ */ dollar: /^[$0-9]+/, /* [0-9]+ */ numericNotRequired: /^\d$/, decimal: /^[0-9\.,]+$/, decimalNotRequired: /^[0-9\.,]$/, alphabet: /^[A-Za-z]/, alphabetWithUnderscore: /^[A-Za-z_]/, alphabetWithSpace: /^[A-Za-z ]/, alphanumeric:/^([a-z]|\d|\s|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+$/i, /*[A-Za-z0-9] */ alphanumericWithUnderscore : /^[A-Za-z0-9_]$/, alphanumericWithSpace: /^[A-Za-z0-9 ]$/, year:/^\d+$/, /* [0-9]+ */ month:/^\d+$/, /* [0-9]+ */ day:/^\d+$/, /* [0-9]+ */ nopobox: /^[^p]{1}[^.]*[^o]{1}[^.]*[^ ]*[^b]{1}[^o]{1}[^x]{1}$/i //physicalAddress: /^[0-9a-zA-Z,. @#$%&*\'`_-]*$\" / } }; var errorsMessage = { en :{ empty: '100', selected:'101', checked: 'Please check', username: 'Valid Usernmae', password: 'Valid Password', email: 'Please enter a valid email address', ip: 'has wrong format. Example: 111.111.111.111', date: 'has wrong format. Example: mm/dd/yyyy', datetime: 'has wrong format. Example: mm/dd/yyyy hh:mm', phone: 'Please enter valid phone number (Ex: 4045551234)', zipUS: 'enter valid USA zipcode.', zipCanada: 'has wrong format. Example: A6A 6A6', zip: 'enter valid USA zipcode.', creditCard: 'credit card number (digits only)', expDateCard: 'enter correct expiration date', cvvnum: 'enter correct 3-digit number', cvv: 'enter correct 3-digit number', numeric: '255', numericNotRequired: 'will allow only numeric', decimal: 'has wrong format', decimalNotRequired: 'has wrong format', cityUS: 'will allow only USA cities', alphabet: 'will allow only alphabet', alphabetWithUnderscore: 'will allow only alphabet with underscore', alphabetWithSpace: 'will allow only alphabet with whitespace', alphanumeric: 'will allow only alphanumeric', alphanumericWithUnderscore : 'will allow only alphanumeric with underscore', alphanumericWithSpace: 'will allow only alphanumeric with whitespace', year:'Please provide valid Year', month:'Please provide valid Month', yearId:'Four-Digit Year', monthId:'Two-Digit Month', dayId:'Two-Digit Day', nopobox: 'No P.O. Boxes Allowed with Fed Ex', correctOrderID:'Please provide a valid Order ID', name: 'Only allow alphabet for names', purchaserFirstname:' Enter valid purchaser first name', purchaserLastname:'Enter valid purchaser last name', physicalAddress:' has wrong Address', purchaserName:'Name on Card is required', homeusername:'Enter valid username', homepassword:'Enter valid password', minlength: '200' }, es:{ empty: 'Por favor introduzca válida', selected:'se debe seleccionar', checked: 'se debe comprobar', email: 'Dirección de correo electrónico no vàlida.', ip: 'tiene un formato incorrecto. Ejemplo: 111.111.111.111', date: 'tiene un formato incorrecto. Ejemplo: mm/dd/yyyy', datetime: 'tiene un formato incorrecto. Ejemplo: mm/dd/yyyy hh:mm', phone: 'Por favor, introduzca el número de teléfono válido Ejemplo: 1234567890', zipUS: 'tiene un formato incorrecto. Ejemplo: 10001', zipCanada: 'tiene un formato incorrecto. Ejemplo: A6A 6A6', zip: 'tiene un formato incorrecto. Ejemplo.', creditCard: 'tiene formato de número equivocado (digits only)', numeric: 'permitirà sólo numérico', number: 'permitirà sólo numérico', numericNotRequired: 'will allow only numeric', decimal: 'tiene formato incorrecto', decimalNotRequired: 'tiene formato incorrecto', alphabet: 'will allow only alphabet', alphabetWithUnderscore: 'will allow only alphabet with underscore', alphabetWithSpace: 'will allow only alphabet with whitespace', alphanumeric: 'will allow only alphanumeric', alphanumericWithUnderscore : 'will allow only alphanumeric with underscore', alphanumericWithSpace: 'will allow only alphanumeric with whitespace', year:'Proporcione Año válida', month:'Proporcione Mes válida', yearId:'Proporcione Año válida', day:'Please provide valid Day', monthId:'Proporcione Mes válida', dayId:'Proporcione Mes vádia', homeusername:'Problemo en llama', homepassword:'Introduzca la contraseña vàlida', minlength: '200' } }; function validateElement(formRef,fieldref){ var totalErrormsg=""; var $fieldref = $(fieldref); var req = $fieldref.attr("mandatory"); var minlength = $fieldref.attr("minlength"); req = (req!=undefined && (req=="required" || req+"" == "true"))?true:false; var validateType = $fieldref.attr("validate"); var errorMsg = ""; var tagType = $fieldref.prop("type").toLowerCase(); var tagName = $.trim($fieldref.prop("tagName")).toLowerCase(); var group= $fieldref.attr("group"); var placeholder = $fieldref.attr('placeholder'); var value = $.trim($fieldref.val()); $fieldref.val(value); var mergeError = $fieldref.attr("mergeError"); var mismatchederror = "Mismatched field"; //alert("errorMsg"+errorMsg); //alert("totalErrormsg"+totalErrormsg.length); var mergeErrorFlag = true; if(!$fieldref.is(":visible")) {return true;} //*new style for error Messages*/ var errorMessageId = $fieldref.attr("errorMessageId"); if(errorMessageId){ $("#"+errorMessageId).empty(); } //*new style for error Messages*/ if(req){ if(tagType=="text" || tagName=="textarea" || tagType=="password"){ if(placeholder!=undefined && $.trim(placeholder)==value){ value = ""; } if(value.length==0){ errorMsg = validatejson.errors.empty; } //*new style for error Messages*/ else if(minlength && !(value.length == minlength)){ errorMsg = (validatejson.errors.minlength).replace("number",minlength); } //*new style for error Messages*/ }else if(tagType=="radio" && !$fieldref.is(":checked")){ var radioFlag = false; if($fieldref.attr("name")!=undefined){ radioFlag = $("input[type=radio][name="+$fieldref.attr("name")+"]").is(":checked"); } if(!radioFlag){ errorMsg = validatejson.errors.checked; } }else if(tagType=="checkbox" && !$fieldref.is(":checked")){ errorMsg = validatejson.errors.checked; } else if((tagName=="select")){ if(mergeError!=undefined){ $("select[mergeError="+mergeError+"]").each(function(index, element) { var innerVal = $.trim($(this).val()); if(innerVal.length==0 || (innerVal+"") == "-1"){ errorMsg = validatejson.errors.selected; alert('you got errors here buddy'); } }); }else if((""+$fieldref.val())=="-1" || $.trim($fieldref.val())==""){ errorMsg = validatejson.errors.selected; } } } if(errorMsg.length==0){ if(tagType=="text" || tagType=="password" || tagName=="textarea"){ var value = $fieldref.val(); if(placeholder!=undefined && $.trim(placeholder)==value){ value = ""; } if(value.length>0){ if(validateType!=undefined && (validatejson.formats[validateType])!=undefined && value.match((validatejson.formats[validateType]))==null){ errorMsg = validatejson.errors[validateType]; }else if(validateType!=undefined && (validateType=="month" ||validateType=="year" || validateType=="date" || validateType=="datetime") && !isValidateDateTime(value,validateType) ){ errorMsg = validatejson.errors[validateType]; }else if($fieldref.attr("maxlength")!=undefined && value.length>$fieldref.attr("maxlength")){ errorMsg ="length should not exceed "+maxlength+" characters"; }else { if(group!=undefined){ $("#"+formRef).find("*[group="+group+"]").each(function(){ if(value!=$.trim($(this).val()) && errorMsg.length==0){ errorMsg = mismatchederror; }else{ var errormsg = $(this).attr("errorMsg"); var prevErrorMsg; if(errormsg!=undefined){ prevErrorMsg= $("#"+$.trim($(this).attr("id"))+"error"); }else{ prevErrorMsg = $(this).parent().find("span.error"); } if((prevErrorMsg!=undefined &&($.trim(prevErrorMsg.text())==$.trim(mismatchederror)))){ prevErrorMsg.hide( "fast").remove(); } } }); } } } } } $("#"+$fieldref.attr("errorMsg")).html(""); $fieldref.parent().find("span.error").hide( "fast").remove(); // alert('turnon dis-able feature'); var flag = true; if(errorMsg.length>0){ //totalErrormsg = ($fieldref.attr("title")==undefined?$fieldref.attr("name"):$fieldref.attr("title"))+" "+errorMsg; totalErrormsg = ($fieldref.attr("title")==undefined?"":$fieldref.attr("title"))+" "+errorMsg; var errormsg = $fieldref.attr("errorMsg"); var errorMsgLocationTag = $fieldref.attr("errorTagClass"); var groupLocation = $fieldref.attr("grouperrorlocation"); //*new style for error Messages*/ if(errorMessageId){ $("#"+errorMessageId).html(totalErrormsg); flag=false; } //*new style for error Messages*/ else if(group && groupLocation==undefined && errorMsg == mismatchederror){ var otherRef = $("[group="+$fieldref.attr("group")+"][grouperrorlocation=true]"); if(otherRef!=undefined && otherRef.val().length > 0){ otherRef.trigger("blur"); } flag=true; }else if(errorMsgLocationTag==undefined){ if(errormsg!=undefined){ $("#"+$.trim($fieldref.attr("id"))+"error").hide( "fast").remove(); var diverrorgen = $("<div/>").css("color","#D00").hide().addClass("error").html(totalErrormsg).attr("id",$.trim($fieldref.attr("id"))+"error"); //var divtext = "<div id='"+$.trim($fieldref.attr("id"))+"error'>"+totalErrormsg+"</div>"; $("."+errormsg).append(diverrorgen).css("color","#D00").hide().show("fast"); alert('turnon dis-able location feature'); }else{ // Bolt Notification Called and Enabled here // if(BoltNotify == true){ // var spanerrorgen = $('.error.message').contents().find('h4').html(totalErrormsg); // VanillaReload.notify.showNotification(".error"); // }else{ // var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(totalErrormsg); // $fieldref.parent().append(spanerrorgen) // spanerrorgen.show("fast"); // } var errorCode = totalErrormsg; _getErrorMessage(errorCode); _stripFields(); $("#button-2").addClass("disabled"); $(".button-2").addClass("disabled"); $("p.links").addClass("disabled"); $(".field.select").addClass("errors"); if(req === false){ $fieldref.removeClass("error"); $fieldref.removeAttr("errorMsg"); $fieldref.removeAttr("class"); }else{ $fieldref.addClass("error"); } $fieldref.removeClass("success"); //$(validatejson.errors.empty).html('Please enter a valid' +$fieldref); //$(validatejson.errors.empty == 'Please enter a valid' +$fieldref); $("input[name*='address2']").removeClass("error"); $("input[name*='emailAddress2']").removeClass("error"); $('input[name^="shippingmethod"]').removeClass("error"); $("select[name*='selectProductAddress']").removeClass("error"); $("input[type='button']").addClass("disabled"); $("button[type='submit']").addClass("disabled"); $("button[type='submit']").attr("disabled", true); $("input[type='button']").attr("disabled", true); $('input[type="submit"]').addClass("disabled"); //$('input[type="Submit"]').attr('disabled','disabled'); $('input[type="submit"]').attr('disabled', true); } }else{ if(errormsg!=undefined){ $("."+errorMsgLocationTag).find("span.error").hide( "fast").remove(); }else{ if($fieldref.attr("customErrorMsg")!=undefined){ totalErrormsg= $fieldref.attr("customErrorMsg"); }else if($fieldref.attr("prefixErrorMsg")!=undefined){ totalErrormsg =$fieldref.attr("prefixErrorMsg")+totalErrormsg; } var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(totalErrormsg); $("."+errorMsgLocationTag).html(spanerrorgen) spanerrorgen.show("fast"); //alert('radio'); } } flag = false; } //*new style for error Messages*/ var otherRef = $("[group="+$fieldref.attr("group")+"]"); if(req === true && flag===true){ $fieldref.removeClass("error"); if(!$fieldref.hasClass("success")){$fieldref.addClass("success");}; if(otherRef){ otherRef.each(function(){ $(this).removeClass("error"); if(!$(this).hasClass("success")){$(this).addClass("success");}; }); } }else if(flag === false){ $fieldref.removeClass("success"); if(!$fieldref.hasClass("error")){$fieldref.addClass("error");}; if(otherRef){ otherRef.each(function(){ $(this).removeClass("success"); if(!$(this).hasClass("error")){$(this).addClass("error");}; }); } }else{ $(this).removeClass("success").removeClass("error"); } //*new style for error Messages*/ return flag; } //*new style for error Messages*/ //var jsonErrors = frontEndErrorCodes; //JC wrote. //MG added. To retrieve Front-end error codes as well as //Backend Error Codes function _getErrorMessage(errorCode, message){ var errorData = JSON.stringify({error_code: errorCode, message: message}); var dataString = $.parseJSON(errorData); $.ajax({ url: './retrieveErrorMessage.json', type: 'POST', data: dataString, dataType: "json", contentType: 'application/json', mimeType: 'application/json', success: function(data) { //data = $.parseJSON(data); // console.log(data); // console.log(errorCode); // console.log(data.error_messages_m); var message = ""; $.each(data.error_messages_m, function(error_code, message ) { if(errorCode == message.error_code && errorCode != -1 ){ console.log(errorCode + message.error_code); console.log(message.message); message = message.message; return false; } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice ==true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }); }, error: function(data) { //data = $.parseJSON(data); console.log(data); console.log(errorCode); console.log(data.message); //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.error_messages_m); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice == true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, fail: function(jqXHR, textStatus) { alert(data); if(textStatus == "parsererror"){ return "We're Sorry a system error occured"; } } }); } function isValidateDateTime(value,type){ value = $.trim(value); if(type=="year"){ var year = (new Date().getFullYear()-parseInt(value,10)); //alert(year); return (year>=18 && year<=150); } if(type=="month"){ var month = parseInt(value,10); //alert(month); return (month>=1 && month<=12); } var maxlength = 10; //date if(type==validatejson.formats.date && value.length == 10){ return isValidateDate(value); }else if(type==validatejson.formats.datetime && value.length == 19){ var datetimestr = value.split(" "); if(datetimestr.length == 2){ return (isValidateTime(datetimestr[1])&&isValidateDate(datetimestr[0])); } } return false; } function isValidateTime(value){ var timearr = value.split(":"); if(!(timearr.length==3 && timearr[0]<24 && timearr[0]>-1 && timearr[1]<60 && timearr[1]>-1&& timearr[2]<60 && timearr[2]>-1)){ return false; } return true; } function isValidateDate(value){ if(value == '') return false; var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex var dtArray = value.match(rxDatePattern); // is format OK? if (dtArray == null) return false; //Checks for mm/dd/yyyy format. dtMonth = dtArray[1]; dtDay= dtArray[3]; dtYear = dtArray[5]; if (dtMonth < 1 || dtMonth > 12) return false; else if (dtDay < 1 || dtDay> 31) return false; else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) return false; else if (dtMonth == 2){ var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0)); if (dtDay> 29 || (dtDay ==29 && !isleap)) return false; } return true; } function languageMessage(lang){ validatejson.errors=((errorsMessage[lang]!=undefined)?errorsMessage[lang]:errorsMessage['en']); } function bindValidation(formRef,lang){ //alert("#"+formRef); languageMessage(lang); $("#"+formRef).find("input:text,input:password,input:radio,input:checkbox,select,textarea").focus(function(){ $(this).parent().find("span.error").hide( "fast").remove(); $(this).parent().find(".field.select.errors").hide( "fast").remove(); $("#"+$.trim($(this).attr("id"))+"error").hide( "fast").remove(); $(".buttonTwo").removeClass("disabled"); $("#button-2").removeClass("disabled"); $(".button-2").removeClass("disabled"); $(".field.select").removeClass("errors"); //$(".ssntip2").removeClass("errors"); //$(".securityCodetip2").removeClass("errors"); //$("form#account_signin_form .button.alternate.username.password").css("top", "10px"); $('input[type="submit"]').removeAttr('disabled'); $('input[type="submit"]').removeClass("disabled"); $("button[type='submit']").removeClass("disabled"); $("button[type='submit']").removeAttr("disabled", true); }); $("#"+formRef).find("input:text,input:password,input:radio,input:checkbox,select,textarea").blur(function(){ //alert("sai"); validateElement(formRef,this); }); $("select[name='alternateIdType']").change(function(e){ String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, '');} $("input[name='identificationNumber']").parent().find("span.error").remove(); $("input[name='alternateIdNumber'],select[name='selectBoxExpMonth'],select[name='selectBoxExpDay'],select[name='selectBoxExpYear']").parent().find("span.error").remove(); var mandatory = true; if(($(this).val().trim()+'')=== '-1'){ $("input[name='identificationNumber']").attr("validate","number").attr("mandatory",mandatory); $("input[name='alternateIdNumber'],select[name='selectBoxExpMonth'],select[name='selectBoxExpDay'],select[name='selectBoxExpYear']").removeAttr("validate","number").removeAttr("mandatory",true); }else{ mandatory = false; $("input[name='identificationNumber']").removeAttr("validate","number").removeAttr("mandatory",mandatory); $("input[name='alternateIdNumber'],select[name='selectBoxExpMonth'],select[name='selectBoxExpDay'],select[name='selectBoxExpYear']").attr("validate","alphanumeric").attr("mandatory",true); } //*new style for error Messages*/ if($(this).hasClass("parent")){ $("[dependency="+$(this).attr("dependency")+"].child").each(function(e){ var dependencymandatory = $(this).attr("mandatory"); if( dependencymandatory === true){ if(this.value){ $(this).removeClass("error"); if(!$(this).hasClass("success")){$(this).addClass("success");}; }else{ $(this).removeClass("success"); if(!$(this).hasClass("error")){$(this).addClass("error");}; } }else{ $(this).removeClass("success").removeClass("error"); } }); } });//*new style for error Messages*/ $("select[name='alternateIdType']").trigger("change"); _stripFields(); } //Submit. Disable and call to modalpoplite for loading the wait page //MG added these features in here so that Jquery Can be used on any site built from here moving forward //Can be modified id known more about jQuery, feel free to update as see fit, if you*r b:tt3r d4n |'|3 //Sai S.. Added the validation. Great Job Sai!!!! :-) function isValidation(formRef,lang){ //alert("#"+formRef); languageMessage(lang); var status = true; $("#"+formRef).find("input:text,input:password,input:radio,input:checkbox,select,textarea").each(function(){ var innerstatus = validateElement(formRef,this); _stripFields(); if(!innerstatus){ status=false //alert('form submitting here'); $("input[name*='address2']").removeClass("error"); $("input[name*='emailAddress2']").removeClass("error"); $("button[type='submit']").addClass("disabled"); $("button[type='submit']").attr("disabled", true); $("#UserLogin").addClass("disabled"); $("#profileSubmitButton_en").addClass("disabled"); $("#profileSubmitButton").addClass("disabled"); $('input[type="submit"]').addClass("disabled"); $('input[type="submit"]').attr("disabled", true); $("input[type='button']").addClass("disabled"); $("button[type='submit']").addClass("disabled"); }else{ //alert('this form is submitting now'); $("input[name*='address2']").removeClass("error"); $("input[name*='emailAddress2']").removeClass("error"); $("select[name*='selectProductAddress']").removeClass("error"); $("button[type='submit']").attr("disabled", true); $("button[type='submit']").addClass("disabled"); $('input[type="submit"]').addClass("disabled"); //$('#loading-div-background').modalPopLite({ openButton: '#clicker', closeButton: '#close-btn', isModal: true }); } }); return status; //var flag=false; //formResult= $("#"+formRef).find.each(function(){ flag=true; alert(flag);});("span.error")==undefined?true:false; //alert("formResult....."+formResult); //return formResult; ////alert("message..."+$("#"+formRef).find("span.error").attr("class")); // return $("#"+formRef).find("span.error").attr("class")==undefined?true:false; } function isHomeValidation(formRef,lang){ //alert("#"+formRef); languageMessage(lang); var status = true; $("#"+formRef).find("input:text,input:password,input:radio,input:checkbox,select,textarea").each(function(){ var innerstatus = validateElement(formRef,this); //alert("inner" + innerstatus); //alert("status" + status); status = status && innerstatus; }); if(!status){ $(".homeLogin").addClass("disabled"); //$("p.links").hide(); }else{ $(".homeLogin").addClass("disabled"); // $("#UserLogin").removeClass("disabled"); // $("#UserLogin").removeAttr("disabled"); //$('input[type="submit"]').attr('disabled','disabled'); $("#loading-div-home").css({ opacity: 1.0 }); $('#loading-div-home').show(); $('#loading-div-home').css('display', 'block'); } return status; } //MG added this for car customization //01-2014 //This is a seperate validation form function isPayValidation(formRef,lang){ //alert("#"+formRef); languageMessage(lang); var status = true; $("#"+formRef).find("input:text,input:password,input:radio,input:checkbox,select,textarea").each(function(){ var innerstatus = validateElement(formRef,this); _stripFields(); if(!innerstatus){ status=false //alert('form submitting here'); //$("#place_order").attr("disabled", true); $('#application_submit_order').addClass('hasErrors'); $('#application_submit_order').removeClass('noErrors'); $("input[name*='address2']").removeClass("error"); $('input[type="submit"]').addClass("disabled"); $('input[type="submit"]').attr('disabled','disabled'); }else{ $('#application_submit_order').removeClass('hasErrors'); $('#application_submit_order').addClass('noErrors'); $("#place_order").addClass("disabled"); //return false; } }); return status; $("input[name*='address2']").removeClass("error"); } //MG.added 07/2014. J.C. Coded this //Strips non numeric characters from the given input field. function _stripFields() { stripChars('pinNumber', /\D/g); stripChars('txtCardNum', /\D/g); stripChars('amt', /\D/g); stripChars('txtZip', /\D/g); stripChars('txtPhone', /\D/g); stripChars('phone', /\D/g); stripChars('cardNum', /\D/g); stripChars('siccode', /\D/g); stripChars('postalcode', /\D/g); } /** * Strips non numeric characters from the given input field. * @param {[type]} input the input field to be stripped. * @param {[regex]} regex string of allowed characters /\W/g for alphanumeric /\D/g for digits * @return {[type]} none */ function stripChars(input, regex){ var originalMaxLength = $('#' + input).attr('maxlength'); $('#' + input).on('keyup', function (event) { if(!(event.keyCode <= 46)) { var val = $( this ).val(); $( this ).val(charStripper(val, originalMaxLength, regex)); $( this ).attr('maxlength', originalMaxLength); } }); $('#' + input).on('paste', function() { $(this).attr('maxlength', 100); element = $(this); setTimeout(function() { var val = element.val(); element.val(charStripper(val, originalMaxLength, regex)); element.attr('maxlength', originalMaxLength); }, 100); }); } /** * Removes all non numeric characters from a string and shortens the string to the max length of the input field being used. * @param {[type]} str The string to be stripped. * @param {[type]} maxlength The max length of the input field being used. * @param {[boolean]} allowLetters If true it strips only special characters. If False it strips all non numeric characters. * @return {[type]} The stripped string. */ function charStripper(str, maxLength, regex) { str = str.replace(regex,''); str = str.substring(0, maxLength); return str; } //Application From Validation Processing //Mg. 07.2014 //Personlize & Customize Validation placed here if($('.manageYourCard').length > 0) { _applyNow(); } function _applyNow(){ // $('*[mandatory="true"]').attr('mandatory', 'false'); // REMOVE Deactivates Front End Validations bindValidation("vrn_form","${pageContext.response.locale}"); $("#btn_load_fund").click(function(){ var result = isValidation("vrn_form","${pageContext.response.locale}"); //alert("Result is now... : [" + result + "]"); if (result == true) { //alert("Let us invoke the JSON call now..."); return false; } else { return false; } }); } //Application From Validation Processing //Mg. 07.2014 //Refund Request Forms //All Three Forms if($('.refundRequest').length > 0) { _refundRequests(); } function _refundRequests(){ // $('*[mandatory="true"]').attr('mandatory', 'false'); // REMOVE Deactivates Front End Validations bindValidation("refundForm","${pageContext.response.locale}"); $("#refundRequestBtn").click(function(){ var result = isPayValidation("refundForm","${pageContext.response.locale}"); if (result == true) { //alert("Let us invoke the JSON call now..."); return false; } else { return false; } }); } //Application From Validation Processing //Mg. 07.2014 //Store Locator Validation if($('.homepageInfo').length > 0) { _locatorNow(); } function _locatorNow(){ // $('*[mandatory="true"]').attr('mandatory', 'false'); // REMOVE Deactivates Front End Validations bindValidation("locator","${pageContext.response.locale}"); $("#btnZip").click(function(){ var result = isValidation("locator","${pageContext.response.locale}"); //alert("Result is now... : [" + result + "]"); if (result == true) { //alert("Let us invoke the JSON call now..."); return false; } else { return false; } }); } //Application From Validation Processing //Mg. 07.2014 //Get Scoop Email Validation if($('.getTheScoop').length > 0) { _getTheScoop(); } function _getTheScoop(){ // $('*[mandatory="true"]').attr('mandatory', 'false'); // REMOVE Deactivates Front End Validations bindValidation("newsletter","${pageContext.response.locale}"); $("#btnGo").click(function(){ var result = isValidation("newsletter","${pageContext.response.locale}"); //alert("Result is now... : [" + result + "]"); if (result == true) { //alert("Let us invoke the JSON call now..."); return false; } else { return false; } }); } Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1489104 Share on other sites More sharing options...
danjapro Posted August 28, 2014 Author Share Posted August 28, 2014 CroNix, Possible you could take a look at entire valdiation script we posted in previous message. Still need help with this. Quote Link to comment https://forums.phpfreaks.com/topic/290642-help-with-getting-error-message/#findComment-1489189 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.