Form Validation with JavaScript and PHP (Not refresh page on submit) - javascript

I am trying to do a form validation with JS that shows feedback as the user types. But of course when submitted the form it's sent using PHP. I already managed to do all of this the only problem I am having now is that when the form is submitted the page refreshes and my "Successfully sent" message cannot be seen. Here is my code and thanks a lot! :D
HTML FORM
<form method="post" id="emailForm" action="?">
<div class="form-group">
<label for="email">Email</label>
<input type="email" placeholder="ejemplo#gmail.com" class="form-control" name="email" id="email"/>
<p class="alert alert-danger errorEmail"></p>
</div>
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" placeholder="María Rodriguez" class="form-control" name="name" id="name"/>
<p class="alert alert-danger errorName"></p>
</div>
<div class="form-group">
<label for="asunto">Asunto</label>
<input type="text" placeholder="Garantía producto" class="form-control" name="asunto" id="asunto" /><span class="badge badgeA"></span>
<p class="alert alert-danger errorAsunto"></p>
</div>
<div class="form-group">
<label for="mensaje">Mensaje</label>
<textarea placeholder="Ingrese su mensaje aquí, trate de ser lo más claro y conciso posible." name="mensaje" id="mensaje" class="form-control" rows="7"></textarea><span class="badge badgeM"></span>
<p class="alert alert-danger errorMensaje"></p>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-success" value="Enviar!"/>
Field to display feedback of submission
<div class="alert alert-success enviado">
</div>
<div class="alert alert-danger noEnviado">
</div>
JavaScript (jQuery)
$(function() {
$(".errorEmail").hide();
$(".errorName").hide();
$(".errorAsunto").hide();
$(".errorMensaje").hide();
$(".enviado").hide();
$(".noEnviado").hide();
var error = false;
$('#email').keyup(function(){
checkEmail();
});
$('#name').keyup(function(){
checkName();
});
$('#asunto').keyup(function(){
checkAsunto();
});
$('#mensaje').keyup(function(){
checkMensaje();
});
function checkEmail() {
var email = $('#email').val();
error = false;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(email)) {
$('.errorEmail').hide();
}
else {
$('.errorEmail').html("Ingrese un correo electrónico válido.")
$('.errorEmail').show();
error = true;
}
}
function checkName() {
var name = $('#name').val().length;
var minName = 5;
var cantidad = - (name - minName);
error = false;
if (name < 5){
$('.errorName').html("Por favor ingrese su nombre. <b>Mínimo " + cantidad + " caracteres.</b>");
$('.errorName').show();
error = true;
}
else {
$('.errorName').hide();
}
}
function checkAsunto() {
var asunto = $('#asunto').val().length;
var minAsunto = 10;
var cantidad = - (asunto - minAsunto);
error = false;
if (asunto <10){
$('.errorAsunto').html("Por favor ingrese un asunto.<b> Mínimo " + cantidad + " caracteres.</b>");
$('.errorAsunto').show();
error = true;
}
else {
$('.errorAsunto').hide();
}
}
function checkMensaje() {
var email = $('#mensaje').val().length;
var minMensaje = 20;
var cantidad = - (email - minMensaje);
error = false;
if (email < 20){
$('.errorMensaje').html("Por favor ingrese un mensaje. <b> Mínimo " + cantidad + " caracteres. </b>");
$('.errorMensaje').show();
error = true;
}
else {
$('.errorMensaje').hide();
}
}
$('#emailForm').submit( function() {
checkEmail();
checkName();
checkAsunto();
checkMensaje();
if(error === false) {
$('.enviado').html("Mensaje enviado exitosamente");
$('.enviado').fadeIn(500);
$('.noEnviado').fadeOut(500);
return true;
} else {
$('.noEnviado').html("Ups... hubo un problema");
$('.noEnviado').fadeIn(500);
$('.enviado').fadeOut(500);
return false;
}
});
});
PHP
The PHP code is really simple some how it doesn't let me display it here but it just get's the $_POST values on the form and sends them using email();
Thanks guys

Instead of returning true replace it with an Ajax post request to the same script, on success show the message you wish.

Related

Two form in one page php, but want to submit only one

I have a page where I have a form for signin and an another for signup.
But when I click either on singin or signup button it's always the signup form who is sent.
Where is my error ?
PHP CODE :
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_POST['modification'] == 1)
{
alert("Signin");
}
if ($_POST['modification'] == 2)
{
alert("Signup");
}
}
HTML CODE :
<div class="col-md-6">
<div class="contact-form">
<form id="connecter" name="connecter" method="post">
<div class="row">
<div class="col-sm-6">
<fieldset>
<input name="txtIdentifiant" type="text" class="form-control" id="txtIdentifiant" placeholder="Identifiant" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtMotDePasse" type="text" class="form-control" id="txtMotDePasse" placeholder="Mot de passe" required="">
</fieldset>
</div>
<div class="col-lg-12">
<fieldset>
<button type="submit" id="btnConnecter" name="btnConnecter" class="filled-button" form="connecter" value="btnConnecter">Se connecter</button>
<input type="hidden" name="modification" value="1" />
</fieldset>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-6">
<div class="contact-form">
<form id="inscrire" name="inscrire" method="post">
<div class="row">
<div class="col-sm-6">
<fieldset>
<input name="txtPrenom" type="text" class="form-control" id="txtPrenom" placeholder="Prénom" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtNom" type="text" class="form-control" id="txtNom" placeholder="Nom" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtGSM" type="text" class="form-control" id="txtGSM" placeholder="Numéro de GSM" required="">
</fieldset>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<fieldset>
<input name="txtAdresseMail" type="text" class="form-control" id="txtAdresseMail" placeholder="Email" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtIdentifiantInscription" type="text" class="form-control" id="txtIdentifiantInscription" placeholder="Identifiant" required="">
</fieldset>
</div>
<div class="col-sm-6">
<fieldset>
<input name="txtMotDePasseInscription" type="text" class="form-control" id="txtMotDePasseInscription" placeholder="Mot de passe" required="">
</fieldset>
</div>
<div class="col-lg-12">
<fieldset>
<button type="submit" id="btnCreerCompte" name="btnCreerCompte" class="filled-button" form="inscrire" value="btnCreerCompte">S'inscrire</button>
<input type="hidden" name="modification" value="2"/>
</fieldset>
</div>
</div>
</form>
</div>
</div>
AJAX CODE :
<script type="text/javascript">
$('#btnConnecter').on('click',function(e){
//prevent submitting form
e.preventDefault();
//Get Input Values
var identifiant = document.getElementById("txtIdentifiant").value;
var motDePasse = document.getElementById("txtMotDePasse").value;
//Form Validation
if (identifiant && motDePasse)
{
//Call Ajax to check if user existed
$.ajax({
type : "POST",
url : "check-signin.php",
dataType: "json",
data:
{
identifiant: identifiant, motDePasse: motDePasse
},
success:function(result)
{
// alert(result.msg);
if (result.msg == "Success")
{
e.preventDefault();
//Submit form if user not existed
$('form').submit();
//alert("Ajax ok");
}
else if (result.msg == "Failed")
{
e.preventDefault();
alert("Identifiant/Mot de passe incorrect");
//C'est chaud
document.getElementById("txtIdentifiant").focus();
return false;
}
else if (result.msg == "Active")
{
e.preventDefault();
alert("Veuillez activer votre compte");
document.getElementById("txtIdentifiant").focus();
return false;
}
}
});
}
else
{
alert("Veuillez remplir tout les champs");
return false;
}
});
</script>
<script type="text/javascript">
$('#btnCreerCompte').on('click',function(e){
e.preventDefault();
var prenom = document.getElementById("txtPrenom").value;
var nom = document.getElementById("txtNom").value;
var mail = document.getElementById("txtAdresseMail").value;
var numGSM = document.getElementById("txtGSM").value;
var minGSM = document.getElementById("txtGSM").length;
var identifiant = document.getElementById("txtIdentifiantInscription").value;
var motDePasse = document.getElementById("txtMotDePasseInscription").value;
if (prenom && nom && mail && numGSM && identifiant && motDePasse)
{
if (isNaN(numGSM) || numGSM.length < 7)
{
alert("Numéro de gsm non valide");
//Phone number invalid
document.getElementById("txtGSM").focus();
return false;
}
else if (validateEmail(mail))
{
$.ajax({
type : "POST",
url : "check-user.php",
dataType: "json",
data: {
identifiant: identifiant
},
success:function(result)
{
if (result.msg == "Success")
{
e.preventDefault();
$('form').submit();
}
else if (result.msg == "Failed")
{
e.preventDefault();
alert("Identifiant déjà existant");
document.getElementById("txtIdentifiantInscription").focus();
return false;
}
}
});
}
else
{
alert("Adresse mail incorrecte");
document.getElementById("txtAdresseMail").focus();
return false;
}
}
else
{
alert("Veuillez remplir tout les champs");
return false;
}
});
</script>
Is it Ajax that break the php submit ?
Because I have the double form in the client section where he can change either his information or his password, and it work over there, I don't know why here it won't work :(
Thank you guys !
do not use button type="submit":
Update to:
<button id="btnCreerCompte" name="btnCreerCompte" class="filled-button" form="inscrire" value="btnCreerCompte">S'inscrire</button>
or:
<input type="button" value="S'inscrire" onclick="submitFormCreerCompte()">
And in the scripts create function "submitFormCreerCompte()" and call ajax to submit form
So I test one or two things, and I somehow make it work like this :
HTML CODE :
<button type="submit" id="btn" name="btn" class="filled-button" form="connecter" value="btnConnecter">Se connecter</button>
<input type="hidden" name="btn" value="btnConnecter" />
<button type="submit" id="btn" name="btn" class="filled-button" form="inscrire" value="btnCreerCompte">S'inscrire</button>
<input type="hidden" name="btn" value="btnCreerCompte"/>
PHP CODE :
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_POST['btn'] == 'btnConnecter')
{
alert("Je suis dedans co");
}
else if ($_POST['btn'] == 'btnCreerCompte')
{
alert("Je suis dedans ins");
}
else
{
alert("Rien fonctionne");
}
}
Thank for the attention guys

Trouble with validation in dynamic forms with jquery + razor pages

I'm working with a form that consists in the following idea, I have courses, each course contains one or n modules.
I created a form that contains a course name and a module. After you saved the module (Click on guardar modulo) the button to add an additional module is enabled, so you can add another one and save it.
By clicking on guardar modulo the modules are saved in an array.
Then, clicking in Crear curso takes the array of modules and the course name and perform a POST. So I saved the course plus its modules.
After completing the fields, if guardar modulo is pressed. The modulo will be stored as explained before.
The issue is that validation is only applied when creating the course (Clicking in crear curso button)
My idea is that validation must be applied when I click on guardar modulo too but It is not applying it.
For simplicity I added the first field of module in the validation (moduleName field).
Here's my code
Index.cshtml
<div class="row">
<div class="col-md-4">
<partial name="_AgregarModuloModal" />
<form>
<div class="form-group">
<label for="cursoName">Nombre Curso</label>
<input type="text"
id="cursoName"
name="cursoName"
class="form-control"
placeholder="Ingrese el nombre del curso"
required />
</div>
<div class="accordion" id="accordion">
<partial name="_ModuloForm" />
</div>
<div class="alert alert-success alert-dismissible fade" id="modulo-added-alert" role="alert">
El módulo ha sido agregado al curso
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<br />
<button type="button" id="showModalForm"> Agregar otro módulo</button>
<br />
<button type="submit" id="submitBtn" class="btn btn-primary">Crear curso</button>
</form>
</div>
</div>
<div>
<a asp-page="Index">Volver</a>
</div>
#section Scripts {
<script>
var modulos = [];
var otherModules = 0;
$(function () {
$('form').validate({
rules: {
cursoName: {
required: true,
minlength: 4,
maxlength: 16
},
moduloName: {
required: true,
minlength: 4,
maxlength: 16
}
},
messages: {
cursoName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
},
moduloName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
}
}
});
var previousForm = $('.card-0').clone(true);
var previousModal = $('#guardar-modulo-modal').clone(true);
$('#modulo-added-alert').css('display', 'none');
$('#showModalForm').prop('disabled', true);
$('#confirm-add-modulo').click(function () {
var id = 'modulo-0';
var modName = $('#moduloName').val();
var modDescripcion = $('#moduloDescripcion').val();
var modEncuentros = $('#moduloEncuentros').val();
var modCupo = $('#moduloCupo').val();
var modCupoTolerancia = $('#moduloCupoTolerancia').val();
var modFechaInicio = $('#moduloFechaInicio').val();
var modFechaFin = $('#moduloFechaFin').val();
var modFechaLimite = $('#moduloFechaLimiteInscripcion').val();
var modalidad = $('#moduloModalidad :selected').text();
// check modules here .. Refactor repeated lines.
const idx = modulos.findIndex(function (mod) {
return mod.id === id
});
if (idx !== -1) {
modulos[idx].nombreModulo = modName;
modulos[idx].descripcionModulo = modDescripcion;
modulos[idx].encuentrosModulo = modEncuentros;
modulos[idx].cupoModulo = modCupo;
modulos[idx].cupoTolerancia = modCupoTolerancia;
modulos[idx].fechaInicio = modFechaInicio;
modulos[idx].fechaFin = modFechaFin;
modulos[idx].fechaLimite = modFechaLimite;
modulos[idx].modalidadModulo = modalidad;
} else {
modulos.push({
id: 'modulo-0',
nombreModulo: modName,
descripcionModulo: modDescripcion,
encuentrosModulo: modEncuentros,
cupoModulo: modCupo,
cupoTolerancia: modCupoTolerancia,
fechaInicio: modFechaInicio,
fechaFin: modFechaFin,
fechaLimite: modFechaLimite,
modalidadModulo: modalidad
});
}
// bad smell --> codigo repetido line --> 190
$('#guardar-modulo-modal').modal('hide');
$('#btn-guardar-modulo').text('Actualizar');
$('#showModalForm').prop('disabled', false);
$('#collapseModButton').addClass('collapsed');
$('#collapseModulo').addClass('collapse');
$('#collapseModulo').removeClass('show');
$('#modulo-added-alert').css('display', 'block');
});
$('#btn-guardar-modulo').click(function () {
// save modulo but first perform validation
$('form').validate({
rules: {
moduloName: {
required: true,
minlength: 4,
maxlength: 16
}
},
messages: {
moduloName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
}
}
});
$('#guardar-modulo-modal').modal('show');
});
$('#showModalForm').click(function (evt) {
evt.preventDefault();
agregarNuevoModulo();
});
function agregarNuevoModulo() {
var newModuloForm = otherModules === 0
? previousForm.clone(true).insertAfter($('.card-0'))
: previousForm.clone(true).insertAfter($('.card-0' + otherModules));
otherModules += 1;
$('#showModalForm').prop('disabled', true);
crearModalAgregarModulo(otherModules);
$.each($('input', newModuloForm), function (i, item) {
$(item).attr('id', $(item).attr('id') + otherModules);
$(item).attr('name', $(item).attr('name') + otherModules);
});
$.each($('select', newModuloForm), function (i, item) {
$(item).attr('id', $(item).attr('id') + otherModules);
$(item).attr('name', $(item).attr('name') + otherModules);
});
var btnAddModulo = $(newModuloForm).find('#btn-agregar-modulo');
$(btnAddModulo).attr('id', $(btnAddModulo).attr('id') + otherModules);
$(newModuloForm).attr('class', $('.card-0').attr('class') + otherModules);
var collapseModuloButton = ($(newModuloForm).find("#collapseModButton"));
$(collapseModuloButton).attr('id', $(collapseModuloButton).attr('id') + otherModules);
$(collapseModuloButton).attr('data-target', '#collapseModulo' + otherModules);
var collapseForm = $(newModuloForm).find("#collapseModulo")
$(collapseForm).attr('id', $(collapseForm).attr('id') + otherModules);
var displayModal = $(newModuloForm).find('#btn-guardar-modulo');
$(displayModal).attr('id', $(displayModal).attr('id') + otherModules);
$(displayModal).attr('data-target', '#guardar-modulo-modal' + otherModules);
}
function crearModalAgregarModulo(otherModules) {
var previousModelId = (otherModules - 1) > 0 ? otherModules - 1 : '';
var clonedModal = previousModal.clone(true).insertAfter('#guardar-modulo-modal' + previousModelId);
$(clonedModal).attr('id', $(clonedModal).attr('id') + otherModules);
var saveModuloBtn = $(clonedModal).find('#confirm-add-modulo');
$(saveModuloBtn).attr('id', $(saveModuloBtn).attr('id') + otherModules);
$(saveModuloBtn).click(function () {
var modName = $('#moduloName' + otherModules).val();
var modDescripcion = $('#moduloDescripcion' + otherModules).val();
var modEncuentros = $('#moduloEncuentros' + otherModules).val();
var modCupo = $('#moduloCupo' + otherModules).val();
var modCupoTolerancia = $('#moduloCupoTolerancia' + otherModules).val();
var modFechaInicio = $('#moduloFechaInicio' + otherModules).val();
var modFechaFin = $('#moduloFechaFin' + otherModules).val();
var modFechaLimite = $('#moduloFechaLimiteInscripcion' + otherModules).val();
var modalidad = $('#moduloModalidad' + otherModules + ':selected').text();
var id = 'modulo-' + otherModules;
const idx = modulos.findIndex(function (mod) {
return mod.id === id
});
if (idx !== -1) {
modulos[idx].nombreModulo = modName;
modulos[idx].descripcionModulo = modDescripcion;
modulos[idx].encuentrosModulo = modEncuentros;
modulos[idx].cupoModulo = modCupo;
modulos[idx].cupoTolerancia = modCupoTolerancia;
modulos[idx].fechaInicio = modFechaInicio;
modulos[idx].fechaFin = modFechaFin;
modulos[idx].fechaLimite = modFechaLimite;
modulos[idx].modalidadModulo = modalidad;
} else {
modulos.push({
id: 'modulo-' + otherModules,
nombreModulo: modName,
descripcionModulo: modDescripcion,
encuentrosModulo: modEncuentros,
cupoModulo: modCupo,
cupoTolerancia: modCupoTolerancia,
fechaInicio: modFechaInicio,
fechaFin: modFechaFin,
fechaLimite: modFechaLimite,
modalidadModulo: modalidad
});
}
$('#guardar-modulo-modal' + otherModules).modal('hide');
$('#btn-guardar-modulo' + otherModules).text('Actualizar');
$('#showModalForm').prop('disabled', false);
$('#collapseModButton' + otherModules).addClass('collapsed');
$('#collapseModulo' + otherModules).addClass('collapse');
$('#collapseModulo' + otherModules).removeClass('show');
$('#modulo-added-alert').css('display', 'block');
});
}
});
</script>
}
_ModuloForm.cschtml
<div class="card card-0">
<div class="card-header" id="moduloForm">
<h5 class="mb-0">
<button class="btn btn-link" id="collapseModButton" type="button" data-toggle="collapse" data-target="#collapseModulo" aria-expanded="true" aria-controls="collapseOne">
Módulo
</button>
</h5>
</div>
<div id="collapseModulo" class="collapse show" aria-labelledby="moduloForm" data-parent="#accordion">
<div class="card-body">
<div class="form-group">
<label for="moduloName">Nombre Modulo</label>
<input type="text" id="moduloName" name="moduloName" class="form-control" placeholder="Ingrese el nombre del módulo" required />
</div>
<div class="form-group">
<label for="moduloDescripcion">Referencia</label>
<input type="text" id="moduloDescripcion" name="moduloDescripcion" class="form-control" placeholder="Ingrese la descripción del modulo" required />
</div>
<div class="form-group">
<label for="moduloEncuentros">Cantidad de encuentros</label>
<input type="number" id="moduloEncuentros" name="moduloEncuentros" class="form-control" placeholder="Ingrese la cantidad de encuentros" required />
</div>
<div class="form-group">
<label for="moduloCupo">Cupo</label>
<input type="number" id="moduloCupo" name="moduloCupo" class="form-control" placeholder="Ingrese el cupo máximo" required />
</div>
<div class="form-group">
<label for="moduloCupoTolerancia">Cupo Tolerancia</label>
<input type="number" id="moduloCupoTolerancia" name="moduloCupoTolerancia" class="form-control" placeholder="Ingrese el cupo de tolerancia" required />
</div>
<div class="form-group">
<label for="moduloFechaInicio">Fecha comienzo</label>
<input type="date" id="moduloFechaInicio" name="moduloFechaInicio" class="form-control" placeholder="Ingrese la fecha de inicio del modulo" required />
</div>
<div class="form-group">
<label for="moduloFechaFin">Fecha finalización</label>
<input type="date" id="moduloFechaFin" name="moduloFechaFin" class="form-control" placeholder="Ingrese la fecha de finalización de módulo" required/>
</div>
<div class="form-group">
<label for="moduloFechaLimiteInscripcion">Fecha límite de inscripción</label>
<input type="date" id="moduloFechaLimiteInscripcion" name="moduloFechaLimiteInscripcion" class="form-control" placeholder="Ingrese la fecha de limite de inscripción" />
</div>
<div class="form-group">
<label for="moduloModalidad">Modalidad</label>
<select id="moduloModalidad" name="moduloModalidad" class="form-control">
<option value="Presencial">Presencial</option>
<option value="Presencial">Virtual</option>
</select>
</div>
<div class="form-group">
<label for="addNewModulo">Guardar Módulo</label>
<button type="button"
class="btn btn-primary button_lenga_primary"
id="btn-guardar-modulo">
Guardar Modulo
</button>
</div>
</div>
</div>
</div>
It's working but partially, if I click on Crear Curso the validation is applied (see image below). But I need to perform a validation in each module when I click on Guardar modulo
Is this possible ? I know code is a mess but I'm going to refactor it after I solve the validation issue.
Because the type of Guardar modulo is button instead of submit, So if you want to show the error message, you need add $("form").valid() in $('#btn-guardar-modulo').click(function () {}) method.
$('#btn-guardar-modulo').click(function () {
// save modulo but first perform validation
$('form').validate({
rules: {
moduloName: {
required: true,
minlength: 4,
maxlength: 16
}
},
messages: {
moduloName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
}
}
});
if($("form").valid()){
//.. modules are saved in an array......
}else{
//.......
}
});

Email Signup Form Modal

I am having trouble when trying to finish a signup form. I've managed to build html code and some js. Can anybody tell me what's missing? Thank You!
<div class="modal" id="email-modal">
<div class="modal-content">
<span class="close-btn">×</span>
<div class="modal-content-left">
<img src="./img/pic1.svg" alt="" id='modal-img' >
</div>
<div class="modal-content-right">
<form action="javascript:Validate(id)" method="GET" class="modal-form" id="form">
<h1>¡Unite a nosotros hoy! Crea tu cuenta completando la información de abajo.</h1>
<div class="form-validation">
<input type="text" class="modal-input" id="name" name="name" placeholder="Ingresá tu nombre">
<p>Error Message</p>
</div>
<div class="form-validation">
<input type="email" class="modal-input" id="email" name="email" placeholder="Ingresá tu mail">
<p>Error Message</p>
</div>
<div class="form-validation">
<input type="password" class="modal-input" id="password" name="password" placeholder="Ingresá tu contraseña">
<p>Error Message</p>
</div>
<div class="form-validation">
<input type="password" class="modal-input" id="password-confirm" name="password" placeholder="Confirmá tu contraseña">
<p>Error Message</p>
</div>
<input type="submit" class="modal-input-btn" value="Sign Up">
<span class="modal-input-login">¿Ya tenes una cuenta? Iniciá sesión acá</span>
</form>
</div>
</div>
</div>
I think it might have something to do with EventListeners. Both the 'name' in checkRequired([name, email, password, passwordConfirm]); and checkLength(name,3,30); appear to be 'deprecated'.
//Modal Items
const modal = document.getElementById('email-modal');
const openBtn = document.getElementById('main__btn');
const closeBtn = document.getElementsByClassName('close-btn')[0];
//Click events
openBtn.addEventListener('click', () => {
modal.style.display = 'block';
});
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (e) => {
if(e.target === modal){
modal.style.display = 'none';
}
});
//Form Validation
const form = document.getElementById('form');
const name = document.getElementById('name');
const email = document.getElementById('email');
const password = document.getElementById('password');
const passwordConfirm = document.getElementById('password-confirm');
//Show error message
function showError(input, message){
const formValidation = input.parentElement;
formValidation.className = 'form-validation error';
const errorMessage = formValidation.querySelector('p');
errorMessage.innerText = message;
}
//Show valid message
function showValid(input){
const formValidation = input.parentElement;
formValidation.className = 'form-validation valid';
}
//Check required fields
function checkRequired(inputArr){
inputArr.forEach(function(input){
if(input.value.trim() === ''){
showError(input,`${getFieldName(input)} is required`);
} else{
showValid(input);
}
})
}
// //Check input lenght
function checkLength(input, min, max){
if(input.value.lenght < min){
showError(input, `${getFieldName(input)} must be at least ${min} characters`);
} else if (input.value.lenght > max) {
showError(input, `${getFieldName(input)} must be less than ${max} characters`);
} else{
showValid(input);
}
}
//Check passwords match
function passwordMatch(input1,input2){
if(input1.value !== input2.value){
showError(input2,'Passwords do not match');
}
}
//Get fieldname
function getFieldName(input){
return input.name.charAt(0).toUpperCase() + input.name.slice(1);
}
//Event Listeners
form.addEventListener('submit', (e) => {
e.preventDefault();
checkRequired([name, email, password, passwordConfirm]);
checkLength(name,3,30);
checkLength(password, 8, 25);
checkLength(passwordConfirm, 8 , 25);
passwordMatch(password, passwordConfirm);
})

Test if a function with multiple if/else blocks return true or false in javascript

I'm not sure if this question has been asked before or not,
I'm trying to make a validation form using Javascript.
My question is: is there any way to test if my functions validateEmailLogin() and validatePsswordLogin() returns true or false in all if/else blocks, so I can test in the function isValide() whether the two functions return true or false and do a treatment.
Ps: it's a bit messy code and any suggestions to reduce it and make it cleaner are welcome.
Here's my html and js code :
function validateEmailLogin() {
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
} else {
emailMessagePatern.classList.add("d-none");
}
}
function validatePsswordLogin() {
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
}
function isValide() {
if (validateEmailLogin() && validatePsswordLogin()) {
window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
return false;
} else {
alert('check your credentials');
}
}
My HTML
form name="loginForm" method="POST">
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small></p>
</div>
<button onclick="return isValide()" type="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
</form>
I like your code!
The message holders = nice!
I've made some modifications:
added valid flag initialized as true, set to false when not valid, and returned from both validate functions
changed isValide to valide and removed the return
removed the <form>
removed type=submit from button
button just calls valide - whatever is needed to be done - from there
commented out change of href for demonstration - uncomment when ready, actually, use location.replace(URL); instead of window.location.href = URL;
Notes:
your URL is a local file...
the email validator function is not complete (x#.com#.com - passes, for example...)
function validateEmailLogin() {
var valid=true;
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
valid=false;
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
valid=false;
} else {
emailMessagePatern.classList.add("d-none");
}
return valid;
}
function validatePsswordLogin() {
var valid=true;
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
valid=false;
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
return valid;
}
function valide() {
if (validateEmailLogin() && validatePsswordLogin()) {
alert("valid");
// window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
} else {
alert('check your credentials');
}
}
.d-none {
display:none;
}
<!-- form name="loginForm" method="POST" -->
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small>
</p>
</div>
<button onclick="valide()" xtype="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
<!-- /form -->

Submit button is not working in Bootstrap form

First of all, I checked the similar posts but didn't find the answer I needed. I can't figure out what is the problem here. I use same form html codes and javascript in seperated files and it works fine but when I integrate those codes into my bootstrap page nothing is happening.
var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;
var unArray = ["Philip", "George", "Sarah", "Michael"];
var pwArray = ["Password1", "Password2", "Password3", "Password4"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
<!-- LOGIN MODAL -->
<div class="modal fade" id="login" role="dialog">
<div class="container">
<div class="modal-dialog">
<div class="row" style="margin-top:20px">
<div class="col-md-12">
<div class="well well-sm">
<form name="myform">
<h2>Please Login</h2>
<div class="form-group">
<input type="text" name="username" class="form-control input-lg" placeholder="Username">
</div>
<div class="form-group">
<input type="password" name="pword" class="form-control input-lg" placeholder="Password">
</div>
<div class="row">
<div class="col-xs-12 col-md-6">
<input type="submit" class="btn btn-lg btn-primary" value="Sign In" onclick="validate()">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END of LOGIN MODAL -->

Categories

Resources