I have a form that when submitted calls a function, but doesn't call the valida_envia()
.
I have the scripts in different files, I call the function valida_envia()
that is located in a file.js
This is my code (also available on JSFiddle )
function valida_envia() {
//Definimos los caracteres permitidos en una dirección de correo electrónico
var regexp = /^[0-9a-zA-Z._.-]+\@[0-9a-zA-Z._.-]+\.[0-9a-zA-Z]+$/;
//Validamos un campo o área de texto, por ejemplo el campo nombre
if (document.form.nombre.value.length == 0) {
alert("Tiene que escribir su nombre");
document.form.nombre.focus();
return 0;
}
if ((regexp.test(document.form.email.value) == 0) || (document.form.email.value.length = 0)) {
alert("Introduzca una dirección de email válida");
document.form.email.focus();
return 0;
} else {
var c_email = true;
}
document.form.submit();
}
<form name="Formulario" action="[email protected]" method="post" onsubmit="return valida_envia()">
name:
<br>
<input type="text" id="nombre" name="nombre">
<br> email:
<br>
<input type="text" id="email" name="email">
<input type="submit" value="Enviar">
</form>
If you review the example
jsfiddle
you will see that you must change where you place the functionin your example you have defined it inside the
onLoad
and that is incorrect, only it in the<head>
Edit the jsfiddle and save the updates, I also put here the example applying the validations
In the case of the JSFiddle, the function is not called because you have the JS code running "onLoad". This causes the function to go inside another function (
$(document).ready(function() {})
) and its scope is limited to within that function. If you change the mode to "No wrap - in <head>" then the function will be calledvalida_envia
.Now, inside that function there are a number of errors:
document.form.nombre
anddocument.form.email
are invalid and give an error, you should use a different notation likedocument.getElementById("nombre")
ordocument.form["nombre"]
return
(the one inlined in the form) interprets 0 as "0", which is not an empty string and so is true and the form will be submitted. Instead it returns true or false .With those changes the code would look like this (you can also see it in JSFiddle ):
There are two main problems: