i have this form:
<form onsubmit="return validarIDC()">
<div class="labelBox">
<div>
<label>Destinatario:</label>
<select name="destinatario">
<option value="hombre">Sr.</option>
<option value="mujer">Sra.</option>
</select>
</div>
<div>
<label>Apellido y<br>nombre:</label>
<input type="text" id="nombre"> *
</div>
<div id="ubicarCampo">
<label>Razón Social:</label>
<input type="text" name="razon">
</div>
<div>
<label>Email:</label>
<input type="email" name="email"> *
</div>
<div>
<label>Teléfono:</label>
<input type="text" name="telefono"> *
</div>
<div>
<label>Celular:</label>
<input type="text" name="celular">
</div>
<div>
<label>Via de Contacto:</label>
<select name="via">
<option value="opc1">E-mail</option>
<option value="opc2">Telefono</option>
<option value="opc3">Correo postal</option>
</select>
</div>
<div>
<label>Comentarios:</label>
<textarea max="300"></textarea>
</div>
<input name="submit" type="submit" value="Enviar">
</div>
</form>
<script type="text/javascript" src="script.js"></script>
and i've done a function to validate all the data from inputs, and it works perfectly exept for one error, more details after the code, here is the JS:
function validarIDC() {
var errores = [];
var er = /^[\w]+$/;
if (document.contactForm.nombre.value == "" || document.contactForm.nombre.value == null) {
errores.push("El nombre es obligatorio.");
}
else if (!er.test(document.contactForm.nombre.value)) {
errores.push("El nombre contiene caracteres no validos o Espacios.");
}
if (document.contactForm.telefono.value == "") {
errores.push("Debe ingresar un telefono")
}
else if (isNaN(document.contactForm.telefono.value)) {
errores.push("El campo telefono contiene caracteres no validos.");
}
if (document.contactForm.email.value == "") {
errores.push("Debe especificar una dirección de Email.");
}
if (document.contactForm.celular.value !== "" && isNaN(document.contactForm.celular.value)) {
errores.push("El campo celular contiene caracteres no validos.");
}
if (errores.length > 0) {
msg = alert("Error/es: \n");
for (var i = 0; i < errores.length; i++) {
msg += errores[i] + "\n";
}
alert(msg);
return false;
}
document.contactForm.submit.disable = true;
alert("Los datos han sido enviados exitosamente!");
return true;
}
So when i submit it pops the alert(msg) but surprisingly when any condition its true i get "undefined" sticked to a side of the errors.. the console log saids nothing and i don't know what am i doing wrong.. please can anyone help me with this ?
You need initialize the variable, since alert() doesn't returns anything msg is undefined.
msg = "Error/es: \n";
instead of
msg = alert("Error/es: \n");
You can use .join()
var msg = "Error/es: \n" + errores.join("\n");
you should specify a name and id to your form...
here is a working code :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form onsubmit="return validarIDC()" name="contactForm" id="contactForm">
<div class="labelBox">
<div>
<label>Destinatario:</label>
<select name="destinatario">
<option value="hombre">Sr.</option>
<option value="mujer">Sra.</option>
</select>
</div>
<div>
<label>Apellido y<br>nombre:</label>
<input type="text" id="nombre" name="nombre"> *
</div>
<div id="ubicarCampo">
<label>Razón Social:</label>
<input type="text" name="razon">
</div>
<div>
<label>Email:</label>
<input type="email" name="email"> *
</div>
<div>
<label>Teléfono:</label>
<input type="text" name="telefono"> *
</div>
<div>
<label>Celular:</label>
<input type="text" name="celular">
</div>
<div>
<label>Via de Contacto:</label>
<select name="via">
<option value="opc1">E-mail</option>
<option value="opc2">Telefono</option>
<option value="opc3">Correo postal</option>
</select>
</div>
<div>
<label>Comentarios:</label>
<textarea max="300"></textarea>
</div>
<input name="submit" type="submit" value="Enviar">
</div>
</form>
<script type="text/javascript">
function validarIDC() {
var errores = [];
var er = /^[\w]+$/;
if (document.contactForm.nombre.value == "" || document.contactForm.nombre.value == null) {
errores.push("El nombre es obligatorio.");
}
else if (!er.test(document.contactForm.nombre.value)) {
errores.push("El nombre contiene caracteres no validos o Espacios.");
}
if (document.contactForm.telefono.value == "") {
errores.push("Debe ingresar un telefono")
}
else if (isNaN(document.contactForm.telefono.value)) {
errores.push("El campo telefono contiene caracteres no validos.");
}
if (document.contactForm.email.value == "") {
errores.push("Debe especificar una dirección de Email.");
}
if (document.contactForm.celular.value !== "" && isNaN(document.contactForm.celular.value)) {
errores.push("El campo celular contiene caracteres no validos.");
}
if (errores.length > 0) {
msg = alert("Error/es: \n");
for (var i = 0; i < errores.length; i++) {
msg += errores[i] + "\n";
}
alert(msg);
return false;
}
document.contactForm.submit.disable = true;
alert("Los datos han sido enviados exitosamente!");
return true;
}
</script>
</body>
</html>
Related
My problem with the following code is that it does not let me enter with the users and passwords of the first three positions of the arrays, but it does let me enter with the last one and I want it to let me enter with each user and their respective password, for example user position 1 with password position 1.
I did it with an if nested in a for and reading the code should work, but it doesn't.
function validar() {
var nombre = document.Formulario.nombre.value;
var password = document.Formulario.password.value;
var indice = document.Formulario.rol.value;
var users = Array('Ruben', 'Juan', 'Pedro', 'Luis');
var pass = Array('1234', 'admin', 'abcd', 'password');
if (nombre == '' || password == '' || indice == 0) {
alert("Faltan campos por llenar");
} else {
alert("Campos llenos :)");
}
for (let i = users.length - 1; i >= 0; i--) {
if (nombre == users[i] && password == pass[i]) {
alert('Bienvenido ' + nombre);
break;
} else {
alert('Datos incorrectos');
break;
}
}
}
<form name="Formulario" method="get" action="recibe.php">
<input type="text" name="nombre" id="nombre" placeholder="Usuario" /><br>
<input type="text" name="password" id="password" placeholder="Password" /><br>
<select name="rol" id="rol">
<option value="0">Selecciona</option>
<option value="1">Gerente</option>
<option value="2">Ejecutivo</option>
</select><br>
<input onclick="validar(); return false;" type="submit" value="Enviar" />
</form>
You can use indexOf for your conditional check instead of using a for loop
function validar(){
var nombre = document.Formulario.nombre.value;
var password = document.Formulario.password.value;
var indice = document.Formulario.rol.value;
var users = Array('Ruben', 'Juan', 'Pedro', 'Luis');
var pass = Array('1234', 'admin', 'abcd', 'password');
if(nombre=='' || password=='' || indice==0){
alert("Faltan campos por llenar");
} else {
alert("Campos llenos :)");
}
if(users.indexOf(nombre) === pass.indexOf(password)) {
alert('Bienvenido ' + nombre);
}
else {
alert('Datos incorrectos');
}
}
<html>
<head>
<title>A8. Validacion de campos con JS + Arreglos_CarlosLomeli</title>
</head>
<body>
<form name="Formulario" method="get" action="recibe.php">
<input type="text" name="nombre" id="nombre" placeholder="Usuario"/><br>
<input type="text" name="password" id="password" placeholder="Password"/><br>
<select name="rol" id="rol">
<option value="0">Selecciona</option>
<option value="1">Gerente</option>
<option value="2">Ejecutivo</option>
</select><br>
<input onclick="validar(); return false;" type="submit" value="Enviar"/>
</form>
</body>
</html>
Use the form submit event
You can use some, to test the user and password
You need to stop the submission when the validation fails
window.addEventListener("DOMContentLoaded", () => { // when page loads
const users = ['Ruben', 'Juan', 'Pedro', 'Luis'];
const pass = ['1234', 'admin', 'abcd', 'password'];
const form = document.Formulario;
form.addEventListener("submit", (e) => {
var nombre = form.nombre.value.trim();
var password = form.password.value.trim();
var indice = form.rol.value.trim();
if (nombre == '' || password == '' || indice == 0) {
alert("Faltan campos por llenar");
e.preventDefault(); // stop submit
return;
}
if (users.some((user, i) => user === nombre && password == pass[i])) {
alert('Bienvenido ' + nombre);
} else {
alert('Datos incorrectos');
e.preventDefault(); // stop submit
return;
}
})
})
<form name="Formulario" method="get" action="recibe.php">
<input type="text" name="nombre" id="nombre" placeholder="Usuario" /><br>
<input type="text" name="password" id="password" placeholder="Password" /><br>
<select name="rol" id="rol">
<option value="0">Selecciona</option>
<option value="1">Gerente</option>
<option value="2">Ejecutivo</option>
</select><br>
<input type="submit" value="Enviar" />
</form>
I have problems with my form submittiting even if the fields are not valid.
I've tried a lot of different code, but I'm currently with this.
const form = document.getElementById('kontaktskjema');
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.errorkontakt');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.errorkontakt');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.errorkontakt')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.errorkontakt')
const navnboks = document.querySelector('.navnboks')
const teleboks = document.querySelector('.teleboks')
const mailboks = document.querySelector('.mailboks')
const messageboks = document.querySelector('.messageboks')
const vernboks = document.querySelector('.vernboks')
const personvern = document.getElementById('checkbox');
const personvernError = document.querySelector('#checkbox + span.errorkontakt')
const submitbtn = document.getElementById('submitbtn');
// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')
email.addEventListener('input', function (event) {
if (email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-ok" )
emailError.innerHTML = '';
emailError.className = 'errorkontakt';
} else {
showError();
}
});
navn.addEventListener('input', function (event) {
if (navn.validity.valid) {
navnError.innerHTML = '';
navnError.className = 'errorkontakt';
navnboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
telefon.addEventListener('input', function (event) {
if (telefon.validity.valid) {
telefonError.innerHTML = '';
telefonError.className = 'errorkontakt';
teleboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
message.addEventListener('input', function (event) {
if (message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-ok" )
messageError.innerHTML = '';
messageError.className = 'errorkontakt';
} else {
showError();
}
})
personvern.addEventListener('change', function (event) {
if (personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
function makeRed() {
if (!navn.validity.valid) {
navnboks.setAttribute("class", "data-validation-error-true")
}
if (!email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-true")
}
if (!telefon.validity.valid) {
teleboks.setAttribute("class", "data-validation-error-true")
}
if (!message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-true")
}
if (!personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-true")
}
};
function divFill() {
if (navnError.textContent != '') {
errOutput.innerHTML += '<li>Navn</li>'
}
if (emailError.textContent != '') {
errOutput.innerHTML += '<li>E-mail</li>'
}
if (telefonError.textContent != '') {
errOutput.innerHTML += '<li>Telefonnummer</li>'
}
if (messageError.textContent != '') {
errOutput.innerHTML += '<li>Beskjed</li>'
}
}
function showError() {
errOutput.innerHTML = ''
if(navn.validity.valueMissing) {
navnError.textContent = '* Du må fylle inn navnet ditt';
navnError.setAttribute("class", "data-validation-error-true" )
} else if(navn.validity.tooShort) {
navnError.textContent = '* Du må fylle inn hele navnet ditt'
}
if(email.validity.valueMissing) {
emailError.setAttribute("class", "data-validation-error-true" )
emailError.textContent = '* Vennligst fyll inn e-posten din';
} else if(email.validity.typeMismatch) {
emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
} else if(email.validity.tooShort) {
emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
}
if(telefon.validity.valueMissing) {
telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
telefonError.setAttribute("class", "data-validation-error-true" )
} else if(telefon.validity.tooShort) {
telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
}
if(message.validity.valueMissing) {
messageError.setAttribute("class", "data-validation-error-true" )
messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
} else if(message.validity.tooShort) {
messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
}
}
emailError.className = 'errorkontakt kontaktactive';
navnError.className = 'errorkontakt kontaktactive';
telefonError.className = 'errorkontakt kontaktactive';
messageError.className ='errorkontakt kontaktactive';
console.log(form)
form.addEventListener('submit', function(event) {
if (!navn.validity.valid || !email.validity.valid || !telefon.validity.valid || !message.validity.valid) {
makeRed();
divFill();
event.preventDefault();
console.log('Runs')
}})
<div id="contact-form-wrapper" class="align-right-50 lazyload">
<div id="contact-form-padding">
<h2>Send oss en melding</h2>
<p><span class="required">*</span> obligatorisk felt som du må fylle ut</p><br>
<div class="errorsOutput">
</div>
<div class="skjema">
<form id="kontaktskjema" action="nyhandler.kontakt.php" method="post" novalidate>
<input type="hidden" id="sendtfra" name="Sidetittel" value="{title}" />
<input type="hidden" id="sendtfraURL" name="Side URL" value="{url}" />
<div class="navnboks">
<p>
<label for="navn">
<span>* Navn:</span>
<input type="text" id="navn" name="navn" required minlength="3" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="mailboks">
<p>
<label for="mail">
<span>* E-post:</span>
<input type="email" id="mail" name="mail" required minlength="6" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="teleboks">
<p>
<label for="telefon">
<span>* Telefonnummer:</span>
<input type="tel" id="telefon" name="telefon" required minlength="8" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="messageboks">
<p>
<label for="message">
<span>* Melding:</span>
<input type="text" id="message" name="message" required minlength="10" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="vernboks">
<input type="hidden" id="recapta" name="g-recaptcha-response" />
<p>
<label for="personvern">
<div class="personvern">
<span>* Personvern:</span>
<br>
<input type="checkbox" id="checkbox" name="checkbox" required>
<span>Jeg har lest og godkjent Personvernserklæringen (åpnes i nytt vindu)</span>
<span class="errorkontakt" aria-live="polite"></span>
</div>
</label>
</p>
</div>
<button type="submit" value="Send" class="button-send">Send</button>
</form>
</div>
</div>
</div>
<div class="clear"></div>
</div>
I know it's weirdly specific, and i'll probably clean it up after i get it to work. Right now the validation completes, and runs the functions makeRed() and divFill(), both functions are there to help with accessability issues when not valid, but the form still submits and goes to the handler php.
Thanks.
getElementsByTagName
will return the form tag's value in [0]th location.
So you might need to change your first line of your javascript code as :
const form = document.getElementsByTagName('form')[0];
It will work .
I`ve building a login page and I would like to redirect the user to another html page only if the Html textbox and password were filled (with anything).
My idea is using only Html and Javascript to do it (as far as I don`t need php to send the data).
So here is my html, the forms part specifically
<form name="frmTeste" onsubmit="return validaForm(this);">
<fieldset id="usuario">
<legend id="usuario" >Identificação do Usuário</legend>
<p>Nº <input type="text" name="tNumero" id="tNumero" size="20" maxlength="15" placeholder="ID"> </p>
<p><label for="cSenha" >Senha:</label> <input type="password" name="tSenha" id="cSenha" size="20" maxlength="12" placeholder="Senha" autocomplete="current-password"/> </p>
<input type="submit" id="botao" class="bt bt-acessar" value="Entrar" onclick="Nova(this)">
<p>
Não possui uma conta? Cadastrar
</p>
</fieldset>
</form>
And here is my javascript
function validaForm(frm) {
if(frm.tNumero.value == "" || frm.tNumero.value == null || frm.tNumero.value.lenght < 3) {
alert("Por favor, indique o seu numero USP.");
frm.nome.focus();
return false;
}else if(frm.cSenha.value == "" || frm.cSenha.value == null || frm.cSenha.value.lenght < 3){
alert("Por favor, indique sua senha");
frm.nome.focus();
return false;
}else{
return true;
}
}
function Nova(frm){
if (validaForm(frm) == false){
location.href = "index.html";
}else if (validaForm(frm) == true){
location.href = "notas.html";
}
I`ve trying a lot of different ways but with no sucess at all.
I think this is what you looking for.
You should change
<form name="frmTeste">
<fieldset id="usuario">
<legend id="usuario" >Identificação do Usuário</legend>
<p>Nº <input type="text" name="tNumero" id="tNumero" size="20" maxlength="15" placeholder="ID"> </p>
<p><label for="cSenha" >Senha:</label> <input type="password" name="tSenha" id="cSenha" size="20" maxlength="12" placeholder="Senha" autocomplete="current-password"/> </p>
<input type="submit" id="botao" class="bt bt-acessar" value="Entrar" onclick="validateForm(this)">
<p>
Não possui uma conta? Cadastrar
</p>
</fieldset>
</form>
Also change the javascript
function validateForm(frm){
window.event.preventDefault();
frm = frm.parentNode.parentNode;
var tNumero = document.getElementById("tNumero");
var cSneha = document.getElementById("cSenha");
if(tNumero.value.length < 3) {
alert("Por favor, indique o seu numero USP.");
window.location.href = "/index.html";
} else if(cSenha.value.length < 3){
alert("Por favor, indique sua senha");
window.location.href = "/index.html";
}else{
frm.setAttribute("action","/notas.html");
frm.submit();
}
}
HTML - this a simple html form, which I have to validate with js, please if some could help me...
<form>
<label class="ancho">Nombre</label>
<input id="name" class="bloque" type="text" placeholder="Nicolas">
<label class="ancho">Apellido</label>
<input id="surename" class="bloque" type="text" placeholder="Oyarzun">
<label class="ancho">Edad</label>
<input id="age" class="bloque" type="number" placeholder="27" min="1" max="110">
<label class="ancho">Carrera</label>
<select id="cbxCarrera" class="bloque">
<option id="op0">-- Seleccione una Carrera --</option>
<option id="op1">Programacion</option>
</select>
<button class="bloque boton" onclick="formulario()">Enviar</button
</form>
JavaScript
<script>
var nombre = document.getElementById("name");
var apellido = document.getElementById("surename");
var edad = document.getElementById("age");
var carrera = document.getElementById("cbxCarrera");
var opcion0 = document.getElementById("op0");
var opcion1 = document.getElementById("op1");
function formulario() {
while (nombre != null || apellido != null || edad > 0) {
if (document.getElementById("cbxCarrera").value != "0") {
// just checking if displays
alert("nombre: " + nombre\ "apellido: " + apellido\ "edad: " + edad\ "carrera: "
document.getElementById(id).optSelected);
}
} else {
alert("Porfavor ingrese valores validos en los campos anteriores.");
}
}
</script>
how can I validate the option selected in the combobox?
thanks!
You can get the selected option by using selectedIndex like this
carrera.options[carrera.selectedIndex];
And then do with it as you please,
REFERENCE
Ok, i have this form:
<div id="reg_mov" title="Agregar Movimiento" style="display:none;">
<form style="width:590px;" method="POST" action="saveMovement.php" onSubmit="return checkFormAndSubmit(this)">
<br>
<input style="display:none;" type="text" name="cliente" value=<?php echo $_GET['cliente']; ?>>
<label>Fecha: </label>
<input type="date" name="fecha_mov" /><br><br>
<label>Inversion del Dia: </label>
<input type="text" name="inversion_mov" />
<label>Tipo de Cambio: </label>
<input type="text" name="tipo_cambio" /><br />
<label>Crecimiento de Fans: </label>
<input type="text" name="fans" />
<input type="checkbox" name="corte" />
<label>Corte</label><br /><br />
<label style="color:#486288; font-size:16px; font-weight:600;">Depósito</label><br><br>
<label>Cantidad: </label>
<input type="text" name="cantidad_deposito" />
<label>Dato de Pago: </label>
<select id="datoPago" name="dato_pago" onChange="checkValue()" ><option>Credito</option><option>Deposito</option></select><br /><br />
<label id="Tarjeta" >Tarjeta: </label>
<input class="Tarjeta" type="text" name="tarjeta" />
<label id="Notas">Notas: </label>
<textarea style="font-size:10px;"cols="30" maxlenght="200" name="notas"></textarea>
<br /><br />
<button style="margin-left:230px;" onClick="submitThisForm(this.form)">Guardar</button>
<button style="margin-left:10px;" onClick="closeDialog()">Cancelar</button>
</form>
And i validate it with this javascript code:
function checkFormAndSubmit(form){
if(form.fecha_mov.value == null || form.fecha_mov.value == "")
{
alert('Selecciona una fecha correcta por favor');
return false;
}
else
{
if(!form.inversion_mov.value.match(/^-?\d+$/) || !form.inversion_mov.value.match(/^-?\d+*\.\d+$/))
{
alert('Ingresa un valor valido para la Inversión del Dia');
return false;
}
else
{
if(!form.tipo_cambio.value.match(/^-?\d+$/) || !form.tipo_cambio.value.match(/^-?\d+*\.\d+$/))
{
alert('Ingresa un valor válido para el Tipo de Cambio');
return false;
}
else
{
if(!form.fans.value.match(/^-?\d+$/))
{
alert('Ingresa un valor válido para el número de Fans');
return false;
}
else
{
if(form.cantidad_deposito.value != "")
{
if(!form.cantidad_deposito.value.match(/^-?\d+$/) || !form.cantidad_deposito.value.match(/^-?\d+*\.\d+$/))
{
alert('Ingresa un valor válido para la Cantidad del Depósito');
return false;
}
else
{
return true;
}
}
}
}
}
}
}
I present the form using jquery UI dialog:
$(function(){
$("#reg_mov").dialog({
height:350,
width:610,
modal:true,
});
});
When i hit the button that i define for submitting it runs the validation and if there's an error it displays the same alert twice and then it still submits the form. How do i stop the submitting thing or what's the right way of doing this validation?