Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

how to fix this "There is a JavaScript error in your browser console" in my catalog,

scl_amorale
Tera Expert
var CSVValidator = Class.create();
CSVValidator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    //  Método principal para validar el archivo CSV adjunto
    getValidarCSV: function () {
        var fileSysId = this.getParameter('sysparm_fileSysId'); //  Obtiene el ID del archivo adjunto

        //  Si no se proporciona un ID de archivo, devuelve un error
        if (!fileSysId) {
            return JSON.stringify({ success: false, message: 'No se encontró un archivo adjunto.' });
        }

        //  Busca el archivo adjunto en la tabla 'sys_attachment'
        var grAttachment = new GlideRecord('sys_attachment');
        if (!grAttachment.get(fileSysId)) {
            return JSON.stringify({ success: false, message: 'El archivo no se encuentra en el sistema.' });
        }

        //  Verifica si el archivo tiene extensión .csv
        if (!grAttachment.file_name.endsWith('.csv')) {
            return JSON.stringify({ success: false, message: 'El archivo debe ser de tipo .csv.' });
        }

        //  Obtiene el contenido del archivo como flujo de datos
        var attachmentStream = new GlideSysAttachment().getContentStream(fileSysId);
        var reader = new GlideTextReader(attachmentStream);
        var line, lineNumber = 0;
        var errores = [];

        //  Procesa el archivo línea por línea
        while ((line = reader.readLine()) !== null) {
            lineNumber++;
            var columns = line.split(',');

            //  Verifica que cada línea tenga exactamente 4 columnas
            if (columns.length !== 4) {
                errores.push('Error en línea ' + lineNumber + ': La fila no tiene exactamente 4 columnas.');
                continue;
            }

            //  Se extraen y limpian los valores de cada columna
            var run = columns[0].trim();
            var correo = columns[1].trim();
            var tipo = columns[2].trim();
            var codigoMinsal = columns[3].trim();

            //  Validaciones individuales para cada campo
            if (!this.validarRUN(run)) {
                errores.push('Error en línea ' + lineNumber + ': RUN inválido (' + run + ').');
            }
            if (!this.validarCorreo(correo)) {
                errores.push('Error en línea ' + lineNumber + ': Correo inválido (' + correo + ').');
            }
            if (!this.validarTipo(tipo)) {
                errores.push('Error en línea ' + lineNumber + ': Tipo inválido (' + tipo + ').');
            }
            if (!this.validarCodigoMinsal(codigoMinsal)) {
                errores.push('Error en línea ' + lineNumber + ': Código Minsal inválido (' + codigoMinsal + ').');
            }
        }

        //  Si hubo errores, los devuelve en el mensaje de respuesta
        if (errores.length > 0) {
            return JSON.stringify({ success: false, message: errores.join(' ') }); //prueba
           
        }

        //  Si no hay errores, el archivo es válido
        //return JSON.stringify({ success: true, message: 'Archivo válido.' });
        return { success: true, message: 'Archivo válido.' };
    },

    //  Método para validar el formato del RUN (cédula de identidad chilena)
    validarRUN: function (run) {
        var runRegex = /^\d{1,2}\.\d{3}\.\d{3}-[0-9kK]$/;
        return runRegex.test(run);
    },

    //  Método para validar el formato del correo electrónico
    validarCorreo: function (correo) {
        var correoRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return correoRegex.test(correo);
    },

    //  Método para validar que el tipo sea "Interno" o "Externo"
    validarTipo: function (tipo) {
        return tipo === 'Interno' || tipo === 'Externo';
    },

    //  Método para validar que el código MINSAL contenga solo números y guiones
    validarCodigoMinsal: function (codigo) {
        return /^[0-9-]+$/.test(codigo);
    },

    type: 'CSVValidator' //  Define el tipo de la clase
});


function onChange(control, oldValue, newValue, isLoading) {
    //  Si la página aún está cargando o el nuevo valor está vacío, se detiene la ejecución
    if (isLoading || newValue === '') {
        return;
    }

    //  Captura el identificador del archivo adjunto (nuevo valor del campo)
    var fileSysId = newValue;
    console.log("📤 Enviando a Script Include - fileSysId:", fileSysId);

    //  Crea una instancia de GlideAjax para llamar al Script Include 'CSVValidator'
    var ga = new GlideAjax('CSVValidator');
    ga.addParam('sysparm_name', 'getValidarCSV'); //  Especifica el método del Script Include
    ga.addParam('sysparm_fileSysId', fileSysId); //  Envía el ID del archivo para su validación
    ga.addParam('sysparm_catalogItemId', '921211c4eb3f46d04efefc6ccad0cdab'); // 📌 ID del ítem de catálogo

    //  Realiza la petición AJAX y procesa la respuesta cuando esté disponible
    ga.getXMLAnswer(function(response) {
        console.log("🔄 Respuesta recibida del servidor:", response);
       
        //  Verifica si la respuesta es válida
        if (!response) {
            console.error(" Error: La respuesta del servidor es NULL o vacía.");
            alert(" Error: La respuesta del servidor es NULL o vacía.");
            return;
        }

        var jsonResponse;
        try {
            //  Intenta parsear la respuesta JSON
            jsonResponse = JSON.parse(response);
        } catch (e) {
            console.error(" Error al parsear JSON:", e);
            alert(" Error al procesar la respuesta del servidor.");
            return;
        }

         //Si la validación falla, muestra un mensaje de error
        if (!jsonResponse.success) {
            console.error(" Error en validación:", jsonResponse.message);
            alert(" " + jsonResponse.message);
        } else {
            //  Si la validación es exitosa, muestra un mensaje de éxito
            console.log(" Archivo válido:", jsonResponse.message);
            alert(" " + jsonResponse.message);
        }
    });
}
 
function onSubmit() {
    var valida = g_form.getValue('submit_valida_csv');

    if (valida == 1) {
        g_form.addErrorMessage(' El archivo no es válido. Por favor, revise los errores.');
        return false; // Bloquea el envío
    }

    var fileSysId = g_form.getValue('adjuntar_csv');

    if (!fileSysId) {
        g_form.addErrorMessage('⚠️ Debe adjuntar un archivo CSV antes de enviar.');
        return false; // Bloquea el envío
    }

    g_form.addInfoMessage(" Validando archivo... Por favor, espere.");

    var gr = new GlideAjax('CSVValidator');
    gr.addParam('sysparm_name', 'getValidarCSV');
    gr.addParam('sysparm_fileSysId', fileSysId);

    gr.getXMLAnswer(function(response) {
        g_form.clearMessages();

        if (!response) {
            g_form.addErrorMessage(' Error: No se recibió respuesta del servidor.');
            return false;
        }

        try {
            var result = JSON.parse(response);

            if (!result.success) {
                g_form.addErrorMessage('⚠️ ' + result.message);
                return false;
            }

            g_form.addInfoMessage(" Archivo válido. Enviando...");
            g_form.submit();

        } catch (e) {
            console.error(' Error procesando respuesta:', e);
            g_form.addErrorMessage('⚠️ Ocurrió un error en la validación del archivo.');
            return false;
        }
    });

    return false; // Bloquea el envío hasta que la validación termine
}


2 REPLIES 2

Nishant8
Tera Sage

Hello @scl_amorale, Which step are you receiving the error message - onLoad or onSubmit? Can you please make a small modification in your Script Include as follows and then try? I'm just commenting out the current return statement and uncommenting the the one that is supposed to be used.

        //  Si no hay errores, el archivo es válido
        return JSON.stringify({ success: true, message: 'Archivo válido.' });
        //return { success: true, message: 'Archivo válido.' };

Debasis Pati
Kilo Sage

Hello @scl_amorale ,

  • Identify the Error Location:

    • Open the browser's Developer Tools (usually by pressing F12 or right-clicking on the page and selecting Inspect).

    • Navigate to the Console tab to view the error messages.

  • Check the Specific Error:

    • Look for the exact error message and the line number where the error occurred. This will help pinpoint the issue.

      Once try the below script:

      var CSVValidator = Class.create();
      CSVValidator.prototype = Object.extendsObject(AbstractAjaxProcessor, {
      // Main method to validate the attached CSV file
      getValidarCSV: function () {
      var fileSysId = this.getParameter('sysparm_fileSysId'); // Gets the attached file ID

      // If no file ID is provided, return an error
      if (!fileSysId) {
      return JSON.stringify({ success: false, message: 'No attached file found.' });
      }

      // Look for the attached file in the 'sys_attachment' table
      var grAttachment = new GlideRecord('sys_attachment');
      if (!grAttachment.get(fileSysId)) {
      return JSON.stringify({ success: false, message: 'The file is not found in the system.' });
      }

      // Verify if the file has a .csv extension
      if (!grAttachment.file_name.endsWith('.csv')) {
      return JSON.stringify({ success: false, message: 'The file must be of type .csv.' });
      }

      // Get the content of the file as a data stream
      var attachmentStream = new GlideSysAttachment().getContentStream(fileSysId);
      var reader = new GlideTextReader(attachmentStream);
      var line, lineNumber = 0;
      var errors = [];

      // Process the file line by line
      while ((line = reader.readLine()) !== null) {
      lineNumber++;
      var columns = line.split(',');

      // Verify that each line has exactly 4 columns
      if (columns.length !== 4) {
      errors.push('Error in line ' + lineNumber + ': The row does not have exactly 4 columns.');
      continue;
      }

      // Extract and clean the values of each column
      var run = columns[0].trim();
      var email = columns[1].trim();
      var type = columns[2].trim();
      var codeMinsal = columns[3].trim();

      // Individual validations for each field
      if (!this.validateRUN(run)) {
      errors.push('Error in line ' + lineNumber + ': Invalid RUN (' + run + ').');
      }
      if (!this.validateEmail(email)) {
      errors.push('Error in line ' + lineNumber + ': Invalid email (' + email + ').');
      }
      if (!this.validateType(type)) {
      errors.push('Error in line ' + lineNumber + ': Invalid type (' + type + ').');
      }
      if (!this.validateCodeMinsal(codeMinsal)) {
      errors.push('Error in line ' + lineNumber + ': Invalid Minsal code (' + codeMinsal + ').');
      }
      }

      // If there were errors, return them in the response message
      if (errors.length > 0) {
      return JSON.stringify({ success: false, message: errors.join(' ') });
      }

      // If there are no errors, the file is valid
      return JSON.stringify({ success: true, message: 'Valid file.' });
      },

      // Method to validate the format of the RUN (Chilean ID number)
      validateRUN: function (run) {
      var runRegex = /^\d{1,2}\.\d{3}\.\d{3}-[0-9kK]$/;
      return runRegex.test(run);
      },

      // Method to validate the email format
      validateEmail: function (email) {
      var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(email);
      },

      // Method to validate that the type is "Internal" or "External"
      validateType: function (type) {
      return type === 'Internal' || type === 'External';
      },

      // Method to validate that the MINSAL code contains only numbers and dashes
      validateCodeMinsal: function (code) {
      return /^[0-9-]+$/.test(code);
      },

      type: 'CSVValidator' // Define the class type
      });

      function onChange(control, oldValue, newValue, isLoading) {
      if (isLoading || newValue === '') {
      return;
      }

      var fileSysId = newValue;
      console.log("📤 Sending to Script Include - fileSysId:", fileSysId);

      var ga = new GlideAjax('CSVValidator');
      ga.addParam('sysparm_name', 'getValidarCSV');
      ga.addParam('sysparm_fileSysId', fileSysId);
      ga.addParam('sysparm_catalogItemId', '921211c4eb3f46d04efefc6ccad0cdab'); // 📌 Catalog item ID

      ga.getXMLAnswer(function(response) {
      console.log("🔄 Server response received:", response);

      if (!response) {
      console.error(" Error: The server response is NULL or empty.");
      alert(" Error: The server response is NULL or empty.");
      return;
      }

      var jsonResponse;
      try {
      jsonResponse = JSON.parse(response);
      } catch (e) {
      console.error(" Error parsing JSON:", e);
      alert(" Error processing the server response.");
      return;
      }

      if (!jsonResponse.success) {
      console.error(" Validation error:", jsonResponse.message);
      alert(" " + jsonResponse.message);
      } else {
      console.log(" Valid file:", jsonResponse.message);
      alert(" " + jsonResponse.message);
      }
      });
      }

      function onSubmit() {
      var validate = g_form.getValue('submit_validate_csv');

      if (validate == 1) {
      g_form.addErrorMessage(' The file is not valid. Please check the errors.');
      return false;
      }

      var fileSysId = g_form.getValue('attach_csv');

      if (!fileSysId) {
      g_form.addErrorMessage('⚠️ You must attach a CSV file before submitting.');
      return false;
      }

      g_form.addInfoMessage(" Validating file... Please wait.");

      var gr = new GlideAjax('CSVValidator');
      gr.addParam('sysparm_name', 'getValidarCSV');
      gr.addParam('sysparm_fileSysId', fileSysId);

      gr.getXMLAnswer(function(response) {
      g_form.clearMessages();

      if (!response) {
      g_form.addErrorMessage(' Error: No response received from the server.');
      return false;
      }

      try {
      var result = JSON.parse(response);

      if (!result.success) {
      g_form.addErrorMessage('⚠️ ' + result.message);
      return false;
      }

      g_form.addInfoMessage(" Valid file. Submitting...");
      g_form.submit();

      } catch (e) {
      console.error(' Error processing response:', e);
      g_form.addErrorMessage('⚠️ An error occurred during file validation.');
      return false;
      }
      });

      return false;
      }

      Please mark it as helpful/correct if this helps you.

      Regards,
      Debasis