I have a very simple form validation, but it doesn't work and I can't see why. When I press submit, it goes to the header of the page instead of displaying the paragraph with the message.
document.getElementById("warning").style.display = 'none';
function validacion() {
let nombre = document.getElementById("campoNombre").value;
let email = document.getElementById("campoEmail").value;
if (nombre === null || email === null || nombre.length === 0 || email.length === 0) {
document.getElementById("warning").style.display = 'block';
return false;
}
};
<div style="text-align:center;">
<h3>Solicitar información</h3>
<form method="POST" id="formulario" onsubmit="return validacion();">
Nombre:<br><input type="text" name="name" id="campoNombre"><br>
Email:<br><input type="text" name="mail" id="campoEmail"><br><br>
<input type="submit" value="Solicitar información" name="submit" id="submit">
</form>
</div>
<div>
<p id="warning">No se enviaron los datos</p>
</div>
Someone can give me a cable?
What happens is that your validations are not entirely correct.
name === null // will never be executed since when you don't write anything it returns an empty string
email.length === "" // the .length returns a number so you should check that it is equal to 0
Example of how I solved it:
Take into account the return false within the onSubmit so that the page does not jump to the beginning
Link to codepen https://codepen.io/renzo-brian-telenta-visconte/pen/ydgzYg
you can validate using
=== ""
in addition to the functiontrim()
to remove spaces, in this way it would work correctly, but you should avoid using the comparison=== null
which would not work correctly:Check the code:
The problem lies in the sentence.
The logical operation
||
has to be given by this for it to work:Given the previous pseudocode, the code would be given by the following operation:
I recommend you use the advantages that HTML provides in cases of form validation, which you can find here .