I have some JS validations in my HTML but the problem is that it directly jumps to PHP before going through the validations.
HTML
<form name="formulario" action="reg.php" method="post" enctype="multipart/form-data" onsubmit="return validar();">
<div class="inicio">
<h1>Registro</h1>
<input type="text" placeholder="Nombre" name="_name" id="_name">
<input type="text" placeholder="Apellido Paterno" name="_lastName" id="_lastName">
<input type="text" placeholder="Apellido Materno" name="_secondName" id="_secondName">
<input type="text" placeholder="Correo" name="_email" id="_email">
<input type="password" placeholder="Contraseña" name="_password" id="_password">
<input type="password" placeholder="Repetir Contraseña" name="_repPassword" id="_rePassword">
<input type="file" class="btn-img" name="up-image" id="up-image">
<div id="preview"></div>
<button class="btn-main">Registrar Usuario</button>
<span><a href="./index.php">Cancelar</a></span>
</div>
</form>
<script src="reg.js"></script>
JS
function validar () {
let name = document.getElementById('_name').value
let lastName = document.getElementById('_lastName').value
let secondName = document.getElementById('_secondName').value
let email = document.getElementById('_email').value
let password = document.getElementById('_password').value
let repPassword = document.getElementById('_repPassword').value
let expresionCorreo = /\w+@\w+\.+[a-z]/
if (
name === '' ||
lastName === '' ||
secondName === '' ||
email === '' ||
password === '' ||
repPassword === ''
) {
alert('Uno o varios campos estan vacios')
return false
} else if (!expresionCorreo.test(email)) {
alert('El correo es invalido')
return false
} else if (password !== repPassword) {
alert('Las contraseñas son diferentes')
return false
}
}
The reason why the form is sent is because you are getting an error
Javascript
when you are looking to get thevalue
fromdocument.getElementById('_repPassword')
, which does not exist.When giving an error, the is never executed
return false
, so thesubmit
continues its normal execution.Solution:
The
id
of the element is_rePassword
( not_repPassword
).demo