Nicolás Nicolás - 3 months ago 9
jQuery Question

JS undefined error when form is submited

i have this form:

<form onsubmit="return validarIDC()">
<div class="labelBox">
<div>
<label>Destinatario:</label>
<select name="destinatario">
<option value="hombre">Sr.</option>
<option value="mujer">Sra.</option>
</select>
</div>
<div>
<label>Apellido y<br>nombre:</label>
<input type="text" id="nombre"> *
</div>
<div id="ubicarCampo">
<label>Razón Social:</label>
<input type="text" name="razon">
</div>
<div>
<label>Email:</label>
<input type="email" name="email"> *
</div>
<div>
<label>Teléfono:</label>
<input type="text" name="telefono"> *
</div>
<div>
<label>Celular:</label>
<input type="text" name="celular">
</div>
<div>
<label>Via de Contacto:</label>
<select name="via">
<option value="opc1">E-mail</option>
<option value="opc2">Telefono</option>
<option value="opc3">Correo postal</option>
</select>
</div>
<div>
<label>Comentarios:</label>
<textarea max="300"></textarea>
</div>
<input name="submit" type="submit" value="Enviar">
</div>
</form>
<script type="text/javascript" src="script.js"></script>


and i've done a function to validate all the data from inputs, and it works perfectly exept for one error, more details after the code, here is the JS:

function validarIDC() {
var errores = [];
var er = /^[\w]+$/;

if (document.contactForm.nombre.value == "" || document.contactForm.nombre.value == null) {
errores.push("El nombre es obligatorio.");
}
else if (!er.test(document.contactForm.nombre.value)) {
errores.push("El nombre contiene caracteres no validos o Espacios.");
}
if (document.contactForm.telefono.value == "") {
errores.push("Debe ingresar un telefono")
}
else if (isNaN(document.contactForm.telefono.value)) {
errores.push("El campo telefono contiene caracteres no validos.");
}
if (document.contactForm.email.value == "") {
errores.push("Debe especificar una dirección de Email.");
}
if (document.contactForm.celular.value !== "" && isNaN(document.contactForm.celular.value)) {
errores.push("El campo celular contiene caracteres no validos.");
}
if (errores.length > 0) {
msg = alert("Error/es: \n");
for (var i = 0; i < errores.length; i++) {
msg += errores[i] + "\n";
}
alert(msg);
return false;
}
document.contactForm.submit.disable = true;
alert("Los datos han sido enviados exitosamente!");
return true;
}


So when i submit it pops the alert(msg) but surprisingly when any condition its true i get "undefined" sticked to a side of the errors.. the console log saids nothing and i don't know what am i doing wrong.. please can anyone help me with this ?

Answer

You need initialize the variable, since alert() doesn't returns anything msg is undefined.

msg = "Error/es: \n";

instead of

msg = alert("Error/es: \n");

You can use .join()

var msg = "Error/es: \n" + errores.join("\n");
Comments