validations with "setCustomValidity" incompatible with alerts - javascript

Im working with forms so need to customize validations with "setCustomValidity" function, the problem comes when i work with alerts and validations in the same.
The button that i use to send my data form got type="submit" when i use that kind my form is making validations correctly but that type makes a refresh so the alert never shows up.
If i switch the type to type="button" then makes the opposite. Validations are not working and alerts finally shows up.
Here is some of the form´s side code:
<div class="modal-dialog">
<div class="modal-content">
<div class="col-12 user-img">
<img src="../../images/nuevoConcesionario.png" alt="">
</div>
<span id="switching1" class="d-none">
<center>
<div class="alert alert-danger" role="alert" id="mensajeError" value="AA">
</div>
</center>
</span>
<form class="formu">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="button" id="bEnviar" class="btn btn-primary" onclick="altaConcesionario();">Dar de alta concesionario</button>
</div>
</div>
</form>
Here is altaConcesionario validation´s function:
function altaConcesionario() {
var nomConcesionario = document.getElementById('nomConcesionario');
var nifConcesionario = document.getElementById('nifConcesionario');
var nomCiudad = document.getElementById('nomCiudad');
var nomAdministrador = document.getElementById('nomAdministrador');
var cpConcesionario = document.getElementById('cpConcesionario');
var telefono = document.getElementById('tlf');
var direccion = document.getElementById('direccion');
var emailConcesionario = document.getElementById('emailConcesionario');
// TODO unificar este mismo patron
var nomConcesionarioPatt = /[A-Za-z0-9]{4,60}/;
var nomCiudadPatt = /[A-Za-z0-9]{4,60}/;
var nomAdminPatt = /[A-Za-z0-9]{4,60}/;
var addrPatt = /[A-Za-z0-9]{4,60}/;
var emailConcesionarioPatt = /^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
var elNif = checkNif(nifConcesionario.value);
var validate = true;
// Nombre concesionario
if (nomConcesionario.value) {
nomConcesionario.setCustomValidity("");
if (!nomConcesionarioPatt.test(nomConcesionario.value)) {
mostrarAlertaValidacion("Error en el ingreso. min[4] caracteres");
nomConcesionario.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomConcesionario.setCustomValidity("Por favor, rellene campo 'nombre concesionario'");
mostrarAlertaValidacion("Por favor, rellene campo 'nombre concesionario'");
validate = false;
}
// Nif concesionario
if (nifConcesionario.value) {
nifConcesionario.setCustomValidity("");
if (!elNif) {
nifConcesionario
.setCustomValidity("El nif introducido no es correcto");
validate = false;
}
} else {
nifConcesionario
.setCustomValidity("Por favor, rellene campo 'NIF concesionario'");
validate = false;
}
// Nombre ciudad
if (nomCiudad.value) {
nomCiudad.setCustomValidity("");
if (!nomCiudadPatt.test(nomCiudad.value)) {
nomCiudad
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomCiudad.setCustomValidity("Por favor, rellene campo 'nombre ciudad'");
validate = false;
}
// Nombre administrador
if (nomAdministrador.value) {
nomAdministrador.setCustomValidity("");
if (!nomAdminPatt.test(nomAdministrador.value)) {
nomAdministrador
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomAdministrador
.setCustomValidity("Por favor, rellene campo 'nombre administrador'");
validate = false;
}
if (direccion.value) {
direccion.setCustomValidity("");
if (!addrPatt.test(direccion.value)) {
direccion
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
direccion.setCustomValidity("Por favor, rellene campo 'direccion'");
validate = false;
}
// Email concesionario
if (emailConcesionario.value) {
emailConcesionario.setCustomValidity("");
if (!emailConcesionarioPatt.test(emailConcesionario.value)) {
emailConcesionario
.setCustomValidity("El email introducido no es correcto. mail#dominio.com");
validate = false;
}
} else {
emailConcesionario
.setCustomValidity("Por favor, rellene campo 'email colaborador'");
validate = false;
}
// TODO falta validacion email
// TODO poner las rewdirecciones en su sitio
// Si estan todos los campos rellenos entra
if (validate) {
// POPUP
// SI TRUE
$
.ajax({
type : "POST",
url : '/proyecto/Api',
data : {
action : 'addConcesionario',
auth_token : auth_token,
usuario_sesion : usuario,
nomConcesionario : nomConcesionario.value,
nifConcesionario : nifConcesionario.value,
nomCiudad : nomCiudad.value,
nomAdministrador : nomAdministrador.value,
cpConcesionario : cpConcesionario.value,
telefono : telefono.value,
direccion : direccion.value,
email : emailConcesionario.value
},
success : function(response) {
alert("EXITO");
window.location.href = "/proyecto/administracion/administracion.jsp";
},
error : function(result) {
alert("ERROR");
window.location.href = "/proyecto/administracion/administracion.jsp";
}
});
}
so i would like to know if there is any reasonable way to make both works together as i need to give information to the final user and is really important for me both of functions.
Thanks in advance,

This happened because you need to prevent form submitting event.preventDefault(). Take a look at example below
const form = document.querySelector('#myForm');
form.addEventListener('submit', ev => {
ev.preventDefault();
//Your code here (validation, http etc)
console.log('Prevented');
})
<form id="myForm">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="submit" class="btn btn-primary">Dar de alta concesionario</button>
</div>
</div>
</form>

Related

Why is my submit button disabled on the first submit attempt and then enabled on the second attempt

I'm working with Bootstrap Validator and a multi-page modal. I have a form inside a multi-page modal and all the validation rules that I set in the JS code are respected, but something curious happens: no matter how many inputs I fill or if there are no inputs that don't respect the validation rules I set, once I try to send the information, the submit button turns disabled; then I have to clear one of the fields that are considered on the validator and fill it back again so that the submit button turns enabled again and once I press it, it finally submits the information.
Here's my BS Validator code:
$('#modalAgregarEmpleado').bootstrapValidator(
{
fields:
{
r_no_empleado:
{
validators:
{
notEmpty:
{
message: 'Campo requerido'
},
remote:
{
url: '/assets/empleados.php'
}
}
},
correo:
{
validators:
{
emailAddress:
{
message: 'Formato de correo electrónico inválido'
}
}
}
}
})
.on('error.field.bv', function(e,data)
{
if(data.bv.getSubmitButton())
{
data.bv.disableSubmitButtons(false);
}
})
.on('status.field.bv',function(e,data)
{
if(data.bv.getSubmitButton())
{
data.bv.disableSubmitButtons(false);
}
});
My HTML code:
<div class="modal fade" id="modalAgregarEmpleado" role="dialog">
<div class="modal-dialog modal-lg">
<form role="form" method="post" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><b>REGISTRO</b></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="modal-split">
<div class="form-row">
<div class="col-md-2 mb-3">
<label for="employee">EMPLOYEE NUMBER:</label>
<input type="number" name="employee" class="form-control" autocomplete="chrome-off">
</div>
<div class="col-md-4 mb-3">
<label for="name">NAME:</label>
<input type="text" name="name" class="form-control" autocomplete="chrome-off">
</div>
<div class="col-md-3 mb-3">
<label for="lastname">LASTNAME:</label>
<input type="text" name="lastname" class="form-control" autocomplete="chrome-off">
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="tel">PHONE NUMBER:</label>
<input type="number" name="tel" class="form-control" autocomplete="chrome-off">
</div>
<div class="col-md-4 mb-3">
<label for="email">E-MAIL:</label>
<input type="email" name="correo" class="form-control" autocomplete="chrome-off">
</div>
</div>
<div class="modal-split">
<div class="form-row">
<div class="col-md-4 mb-3">
<label>DATE:</label>
<input type="text" name="date" id="date" class="form-control" placeholder="aaaa-mm-dd">
</div>
<div class="col-md-4 mb-3">
<label>CLOCK-IN:</label>
<input type="text" name="clockin" id="clockin" class="form-control timepicker" autocomplete="chrome-off">
</div>
<div class="col-md-4 mb-3">
<label>CLOCK-OUT:</label>
<input type="text" name="clockout" id="clockout" class="form-control timepicker" autocomplete="chrome-off">
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</form>
</div>
</div>
My multi-page modal JS code:
$(document).ready(function()
{
prep_modal();
});
function prep_modal()
{
$(".modal").each(function()
{
var element = this;
var pages = $(this).find('.modal-split');
if (pages.length != 0)
{
pages.hide();
pages.eq(0).show();
var b_button = document.createElement("button");
b_button.setAttribute("type","button");
b_button.setAttribute("class","btn btn-primary");
b_button.setAttribute("style","display: none;");
b_button.innerHTML = "BACK";
var n_button = document.createElement("button");
n_button.setAttribute("type","button");
n_button.setAttribute("class","btn btn-primary");
n_button.innerHTML = "NEXT";
var s_button = document.createElement("button");
s_button.setAttribute("type","submit");
s_button.setAttribute("class","btn btn-primary");
s_button.setAttribute("style","display: none;");
s_button.innerHTML = "SAVE";
$(this).find('.modal-footer').append(b_button).append(n_button).append(s_button);
var page_track = 0;
$(n_button).click(function()
{
this.blur();
if(page_track == 0)
{
$(b_button).show();
}
if(page_track == pages.length-2)
{
$(n_button).hide();
$(s_button).show();
}
if(page_track == pages.length-1)
{
$(element).find("form").submit();
}
if(page_track < pages.length-1)
{
page_track++;
pages.hide();
pages.eq(page_track).show();
}
});
$(b_button).click(function()
{
if(page_track == 1)
{
$(b_button).hide();
}
if(page_track == pages.length-1)
{
$(s_button).hide();
$(n_button).show();
}
if(page_track > 0)
{
page_track--;
pages.hide();
pages.eq(page_track).show();
}
});
}
});
}
The HTML part is a translated and compressed version of the actual code. The original code is in Spanish and more extended.

Check the value of an element and take action

I would like a function that checks if some fields of the form have been filled out and if true it would execute a code of mine, if false it would do nothing.
In short, I would like to know how I check the fields, the code that will be executed, I already have it ready.
HTML of the fields I want to check if they have been filled out:
<!-- verifica select -->
<div class="form-group pmd-textfield col-md-4">
<label for="InqueritoCircunscricaoPolicial" class="control-label cssPerguntas espacamentoLabels">
<strong>1.1</strong> Circunscrição policial
</label>
<select asp-for="InqueritoModel.COD_INQUERITO_CIRCUNSCRICAO_POLICIAL "
asp-items="Model.ListCircunscricao"
id="InqueritoCircunscricaoPolicial"
class="select-codigo"
onchange="mostrarOutroDeCombo(this, 'DSC_OUTRO_INQUERITO_CIRCUNSCRICAO_POLICIAL')">
<option value="">Selecione a circunscrição</option>
</select>
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="NumeroDaOcorrencia" class="control-label cssPerguntas espacamentoLabels">
<strong>1.3</strong> Número da ocorrência
</label>
<input class="form-control" id="NumeroDaOcorrencia" maxlength="1000" placeholder="N° da ocorrência"
asp-for="InqueritoModel.NumeroDaOcorrencia"
type="text">
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="DataDaInstauracao" class="control-label cssPerguntas espacamentoLabels">
<strong>1.9</strong> Data da instauração
</label>
<input class="form-control" id="DataDaInstauracao" min="1900-01-01"
asp-for="InqueritoModel.DataDaInstauracao"
type="date">
</div>
My attempt:
function progressBarInq() {
let progressBar0 = document.getElementById("InqProgress0");
let progressBar25 = document.getElementById("InqProgress25");
let progressBar50 = document.getElementById("InqProgress50");
let progressBar75 = document.getElementById("InqProgress75");
let progressBar100 = document.getElementById("InqProgress100");
//25%
let verInq1 = document.getElementById("InqueritoCircunscricaoPolicial");
//50%
let verInq5 = document.getElementById("NumeroDoIP");
//75%
let verInq8 = document.getElementById("DataDoRelatorio");
//100%
let verInq11 = document.getElementById("NumeroDoProcesso");
if (verInq1.value && verInq5.value && verInq8.value && verInq11.value) {
progressBar0.style.display = "none";
progressBar25.style.display = "block";
progressBar50.style.display = "none";
progressBar75.style.display = "none";
progressBar100.style.display = "none";
}
progressBarInq();
verifyonClick = () => {
var first = document.getElementById("InqueritoCircunscricaoPolicial")
var second = document.getElementById("NumeroDaOcorrencia")
var third = document.getElementById("DataDaInstauracao")
if(first.value && second.value && third.value)
alert("Value exist in every input")
else
alert("Please enter value in all fields")
}
<!-- verifica select -->
<div class="form-group pmd-textfield col-md-4">
<label for="InqueritoCircunscricaoPolicial" class="control-label cssPerguntas espacamentoLabels">
<strong>1.1</strong> Circunscrição policial
</label>
<select asp-for="InqueritoModel.COD_INQUERITO_CIRCUNSCRICAO_POLICIAL "
asp-items="Model.ListCircunscricao"
id="InqueritoCircunscricaoPolicial"
class="select-codigo"
onchange="mostrarOutroDeCombo(this, 'DSC_OUTRO_INQUERITO_CIRCUNSCRICAO_POLICIAL')">
<option value="">Selecione a circunscrição</option>
</select>
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="NumeroDaOcorrencia" class="control-label cssPerguntas espacamentoLabels">
<strong>1.3</strong> Número da ocorrência
</label>
<input class="form-control" id="NumeroDaOcorrencia" maxlength="1000" placeholder="N° da ocorrência"
asp-for="InqueritoModel.NumeroDaOcorrencia"
type="text">
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="DataDaInstauracao" class="control-label cssPerguntas espacamentoLabels">
<strong>1.9</strong> Data da instauração
</label>
<input class="form-control" id="DataDaInstauracao" min="1900-01-01"
asp-for="InqueritoModel.DataDaInstauracao"
type="date">
</div>
<div>
<button onclick="verifyonClick()"> submit </button>
</div>

How to valid checkbox in a form

I have a basic question but i can't find the solution .
how can i force my user to check the box : accept the condition ? (j'acceptes les conditions d'utilisations = i agree terms & conditions )
here is a pictures of my form :
here is my HTML:
<section id="formDom">
<form class="column g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Nom</label>
<input type="text" class="form-control" placeholder="Dupont" id="firstName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">prénom</label>
<input type="text" class="form-control" placeholder="Jean" id="lastName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Adresse mail</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="email" class="form-control" id="email" aria-describedby="inputGroupPrepend"
placeholder="jeandupont#gmail.com" required>
<div class="invalid-feedback">
Adresse mail requise
</div>
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Ville</label>
<input type="text" class="form-control" placeholder="Paris" id="city" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom03" class="form-label">Adresse</label>
<input type="text" class="form-control" placeholder="1 rue de Paris" id="adress" required>
<div class="invalid-feedback">
adresse réquise
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
J'accepte les conditions d'utilisations
</label>
<div class="invalid-feedback">
Vous devez accepteer les conditions d'utilisations
</div>
</div>
</div>
<div class="col-md-4">
<button id="buyBtn" class="btn btn-primary basket-btn" type="submit">Acheter</button>
</div>
</form>
</section>
Actually the user is forced to fill the form but he can submit without check the box ( accept condition )
Here is the JS :
function validForm() {
const form = document.querySelector('.needs-validation');
form.addEventListener('submit', function (event) {
event.preventDefault();
event.stopPropagation();
cameraIds = getBasket().map(item => { return item.id });
const contact = {
email: document.getElementById("email").value,
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
city: document.getElementById("city").value,
address: document.getElementById("adress").value,
}
createOrder(contact, cameraIds, (order, error) => {
if (error) {
alert('Merci de remplir le formulaire');
} else {
localStorage.clear();
location.assign(`confirmation.html?id=${order.orderId}`)
}
form.classList.add('was-validated');
})
})
}
validForm();
PS : i'm using BOOTSTRAP but i think you got it ^^
if(document.getElementById('invalidCheck').checked==true)
//you'r accepted the terms
else
//you should accept the terms
You can check if a checkbox is checked or not by testing the checked property of the input element:
var isChecked = document.querySelector('input[type="checkbox"]').checked;
if(!isChecked) {
alert("You must accept the terms before proceeding");
}
In your case, it will be:
var isChecked = document.querySelector('.needs-validation .form-check-input').checked;
You can check for document.getElementById("").checked

JQuery: need to hide div if input file is empty

I need to hide a div for aditional coments if the input file is empty.
I don't mind if it's done with Jquery or plain Javascript.
I've used JQuery, I know that it's been called correctly because my alert pops up, but my function does not hide the div with ID: #instrucciones-adicionales and all its contents.
HTML:
<script>
alert( "Animation complete." );
$(function () {
$("input:file").change(function () {
var fileName = $(this).val();
if (filename != "") {
$("#instrucciones-adicionales").hide();
} //show the button
});
});
</script>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="Ka5bun8eHCmm5pReR7M9JCOxP8YxVq1sBfi79yqnXFEFWEksDE8WSDfgiYxf2KDb">
<div class="form-group">
<div id="div_id_imagenes" class="form-group">
<label for="id_imagenes" class="col-form-label requiredField">
Imagenes<span class="asteriskField">*</span>
</label>
<div class="">
<input type="file" name="imagenes" class="clearablefileinput" required id="id_imagenes">
</div>
</div>
<div id="instrucciones-adicionales">
<p class="bold-font"> Instrucciones adicionales (opcional):</p>
<div id="div_id_instrucciones" class="form-group">
<label for="id_instrucciones" class="col-form-label requiredField">
Instrucciones<span class="asteriskField">*</span>
</label>
<div class="">
<textarea name="instrucciones" cols="40" rows="10" class="textarea form-control" required id="id_instrucciones">
</textarea>
</div>
</div>
</div>
</div>
</br>
</br>
<p>O, sáltate este paso y envía tu arte por correo electrónico</p>
<button type="submit" class="btn btn-naranja text-white btn-block">Continuar
</button>
You had a typo (variables are case sensitive - fileName !== filename).
I added the show part:
alert( "Animation complete." );
$(function () {
$("input:file").change(function () {
var fileName = $(this).val();
if (fileName != "") {
$("#instrucciones-adicionales").hide();
} else {
$("#instrucciones-adicionales").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main role="main">
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="Ka5bun8eHCmm5pReR7M9JCOxP8YxVq1sBfi79yqnXFEFWEksDE8WSDfgiYxf2KDb">
<div class="form-group">
<div id="div_id_imagenes" class="form-group">
<label for="id_imagenes" class="col-form-label requiredField">
Imagenes<span class="asteriskField">*</span>
</label>
<div class="">
<input type="file" name="imagenes" class="clearablefileinput" required id="id_imagenes">
</div>
</div>
<div id="instrucciones-adicionales" style="display: none">
<p class="bold-font"> Instrucciones adicionales (opcional):</p>
<div id="div_id_instrucciones" class="form-group">
<label for="id_instrucciones" class="col-form-label requiredField">
Instrucciones<span class="asteriskField">*</span>
</label>
<div class="">
<textarea name="instrucciones" cols="40" rows="10" class="textarea form-control" required id="id_instrucciones">
</textarea>
</div>
</div>
</div>
</div>
</br>
</br>
<p>O, sáltate este paso y envía tu arte por correo electrónico</p>
<button type="submit" class="btn btn-naranja text-white btn-block">Continuar
</button>
</form>
</main>

Validation of code

I have developed some code in bootstrap and I am getting an error while I was validating the fields (name, email). Please help me out.
This is the code for the form:
<div class="container">
<h3 class="text-center">CONTACT</h3>
<p class="text-center"><em>I love my Fans!</em></p>
<div class="row test">
<div class="col-md-4">
<p><span class="glyphicon glyphicon-map-marker"></span>4429, Rainier Street, Irving, Texas ,United States</p>
<p><span class="glyphicon glyphicon-phone"></span>Phone:Phone</p>
<p><span class="glyphicon glyphicon-envelope"></span>Email: Email</p>
</div>
<div class="col-md-8">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form control" id="name" placeholder="Name" type="text" onBlur="txt_Blur(this,'errorName')" />
<span id="errorName" style="display:none;">Please enter a valid name!</span>
</div>
<div class="col-sm-6 form-group">
<input class="form control" id="email" name="email" placeholder="Email" type="email" required>
<span id="errorName" style="display:none;">Please enter a valid email!</span>
</div>
</div>
<div class="textarea">
<textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>
<span id="errorName" style="display:none">Please enter your comments!</span>
</div>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="btn pull-right" type="submit" onclick="button_Click()">Send</button>
</div>
</div>
</div>
</div>
</div>
The JavaScript for validation below:
function txt_Blur(ref, errorId) {
if (ref.value == "") {
document.getElementById(errorId).style = "color:red;";
} else {
document.getElementById(errorId).style = "display:none;";
}
}
function button_Click() {
if (document.getElementById("name")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
if (document.getElementById("email")).value == "") {
document.getElementById("errorName").style = "color:red;";
} else {
document.getElementById("errorName").style = "display:none;";
}
}
I need the error displayed when someone tries to leave the name field empty and goes to the next text field (email).

Categories