I'm new here at Stack Overflow an I'm also a beginner in programming so please have mercy :)
I'm trying to block with javascript the submission of a multi field form when one or more fields are empty.
Basically, when I submit the form leaving all the fields blank, the error appears only below the first field but nothing happens to the others and the form is sent.
I do apologize in advance as this topic has already been treated several times in other threads but I can't figure out how to make in work.
I'm using the following code (html and js in the same page):
<script type="text/javascript">
function validateForm() {
var a = document.forms["form1"]["nome"].value;
var b = document.forms["form1"]["cognome"].value;
var c = document.forms["form1"]["azienda"].value;
var d = document.forms["form1"]["CF"].value;
var e = document.forms["form1"]["msg"].value;
if (a == ""){
document.getElementById('err_nome').innerHTML += "Il nome è obbligatorio";
return false;}
if (b == ""){
document.getElementById('err_cognome').innerHTML += "Il cognome è obbligatorio";
return false;}
if (c == ""){
document.getElementById('err_azienda').innerHTML += "Il azienda è obbligatorio";
return false;}
if (d == ""){
document.getElementById('err_CF').innerHTML += "Il CF è obbligatorio";
return false;}
if (e == ""){
document.getElementById('err_msg').innerHTML += "Il msg è obbligatorio";
return false;}
}
</script>
<html>
<body>
<?php include ("incl/header.php"); ?>
<div class="menu">
<?php include ("incl/menu.php") ?>
</div>
<div class="column-left">
</div>
<div class="column-center"><br>
<form name="form1" method="post" action="sendmail.php" onsubmit="validateForm()>
<br>
Nome
<input type="text" name="nome">*
<br><span class="error"><div id="err_nome"></div></span><br><br><br>
Cognome
<input type="text" name="cognome">*
<br><span class="error"><div id="err_cognome"></div></span><br><br><br>
Azienda
<input type="text" name="azienda">*
<br><span class="error"><div id="err_azienda"></div></span><br><br><br>
Codice Fiscale
<input type="text" name="CF">*
<br><span class="error"><div id="err_CF"></div></span><br><br><br>
Messaggio
<textarea id="text" name="msg" rows="5" col="40" maxlength="2000"></textarea>*
<br><span class="error"><div id="err_msg"></div></span><br>
<br>
<input type="submit" name="submit" value="submit">
<br><br><br><br><br><br>
</form>
</div>
<div class="column-right">
</div>
<div class="footer">
<?php include "incl/footer.php"; ?>
</div>
</body>
</html>
Many thanks to those of you will help.
Alberto
You have return false; in all your comparisons, that will exit the validateForm() function after the first incorrect field. If you want to validate all fields, keep the result in variable and return it at the end. Like this:
function validateForm() {
var a = document.forms["form1"]["nome"].value;
var b = document.forms["form1"]["cognome"].value;
var c = document.forms["form1"]["azienda"].value;
var d = document.forms["form1"]["CF"].value;
var e = document.forms["form1"]["msg"].value;
var result = true;
if (a == "") {
document.getElementById('err_nome').innerHTML += "Il nome è obbligatorio";
result = result && false;
}
if (b == "") {
document.getElementById('err_cognome').innerHTML += "Il cognome è obbligatorio";
result = result && false;
}
if (c == "") {
document.getElementById('err_azienda').innerHTML += "Il azienda è obbligatorio";
result = result && false;
}
if (d == "") {
document.getElementById('err_CF').innerHTML += "Il CF è obbligatorio";
result = result && false;
}
if (e == "") {
document.getElementById('err_msg').innerHTML += "Il msg è obbligatorio";
result = result && false;
}
return result
}
<html>
<body>
<div class="menu">
</div>
<div class="column-left">
</div>
<div class="column-center"><br>
<form name="form1" method="post" onsubmit="return validateForm()">
<br> Nome
<input type="text" name="nome">*
<br><span class="error"><div id="err_nome"></div></span><br><br><br> Cognome
<input type="text" name="cognome">*
<br><span class="error"><div id="err_cognome"></div></span><br><br><br> Azienda
<input type="text" name="azienda">*
<br><span class="error"><div id="err_azienda"></div></span><br><br><br> Codice Fiscale
<input type="text" name="CF">*
<br><span class="error"><div id="err_CF"></div></span><br><br><br> Messaggio
<textarea id="text" name="msg" rows="5" col="40" maxlength="2000"></textarea>*
<br><span class="error"><div id="err_msg"></div></span><br>
<br>
<input type="submit" name="submit" value="submit">
<br><br><br><br><br><br>
</form>
</div>
<div class="column-right">
</div>
<div class="footer">
</div>
</body>
</html>
Related
Today I have a tricky (for me at least) question. There is a bug in my code, I don't know how to eliminate it. Basically I'm creating a simple Form in JavaScript as an homework, and I encountered this problem.
I have to enter my age in this form, and for now it's all ok. But I have to enter it twice: one with an <input> tag and one with a popup window. I can input the value in the <input> tag just fine, but when I'm trying to input the value by the prompt(), it "resets" the script, so I lose the value in the <input> object.
I need a way to store these information somewhere, or stop the prompt() from deleting these values or resetting the page.
<html lang="en">
<head>
<title>Document</title>
<style>
* {margin: 0; padding: 0;}
body {padding: 20px;}
</style>
<script>
var eta_btn;
function eta_controllo(eta_btn) {
eta_btn = Number(prompt("Inserisci la tua età"));
console.log(eta_btn);
}
function profession() {
var temp = document.getElementById("select").selectedIndex;
if (temp == 0) {
document.getElementById("lavoratore_txt").style.display = "";
document.getElementById("studente_txt").style.display = "none";
} else if (temp == 1) {
document.getElementById("studente_txt").style.display = "";
document.getElementById("lavoratore_txt").style.display = "none";
} else {
document.getElementById("studente_txt").style.display = "none";
document.getElementById("lavoratore_txt").style.display = "none";
}
}
function send_to_server() {
if (!(eta_btn == document.getElementById("età").value)) {
alert("Le due età inserite non sono concordi");
return false;
}
else if (eta_btn == document.getElementById("età").value && eta_btn < 14) {
alert("Hai meno di 14 anni!");
return false;
} else if (confirm("Sicuro di aver scelto la provincia " + document.querySelector('input[name="città"]:checked').value))
alert("Dati inviati correttamente");
else {
alert("Errore");
return false;
}
}
</script>
</head>
<body>
<form action="">
<p>NOME</p>
<input placeholder="scrivi qui il tuo nome" type="text"><br><br>
<p>PASSWORD</p>
<input placeholder="scrivi qui la tua password" type="text"><br><br>
<p>ETA'</p>
<input placeholder="scrivi qui la tua età" type="text" id="età">
<button onclick="eta_controllo()">CONTROLLO</button><br><br>
<input name="città" type="radio">GENOVA<br>
<input name="città" type="radio">SAVONA<br>
<input name="città" type="radio">IMPERIA<br>
<input name="città" type="radio">LA SPEZIA<br><br>
<select name="" id="select" onchange="profession()">
<option value="lavoratore">Lavoratore</option>
<option value="studente">Studente</option>
<option value="disoccupato">Disoccupato</option>
</select>
<p id="studente_txt" style="display: none">Vai a studiare!</p><br>
<textarea id="lavoratore_txt" style="display: none;" name="" id="" cols="30" rows="10"></textarea><br><br>
<button>ANNULLA TUTTO</button>
<button onclick="send_to_server()">INVIA AL SERVER</button>
</form>
</body>
</html>
All you have to do is to add type="button" to the button.
The default type of button is "submit", so when you click it, it will submit the form.
Hi have you already taken a look at this link?
It could be ulile in my opinion ..
there are no global variables to manage the memories ..
The Localstorage of the browser.
I hope I have been of help .. good studyhttps://www.w3schools.com/jsref/prop_win_localstorage.asp
It seems that my "validate" function is not activating for some reason.
I've tried by to use onsubmit and onclick, as well as tried to use ID in the place of name.
The script is already preloaded on head.
function validar() {
var nome = formulario.nome.value;
var email = formulario.email.value;
var cpf = formulario.cpf.value;
var telefone_fixo = formulario.telefone_fixoe.value;
var telefone_celular = formulario.telefone_celular.value;
var login = formulario.login.value;
var senha = formulario.senha.value;
var rep_senha = formulario.rep_senha.value;
if (nome == "") {
alert("Preencha o campo com seu NOME");
formulario.nome.focus();
return false;
}
if (nome.lenght < 5) {
alert("Digite seu NOME COMPLETO");
formulario.nome.focus();
return false;
}
if (cpf.lenght < 11) {
alert("Digite apenas os números do CPF");
formulario.cpf.focus();
return false;
}
if (telefone_fixo < 10) {
alert("Digite apenas os números do TELEFONE");
formulario.telefone_fixo.focus();
return false;
}
if (telefone_celular < 11) {
alert("Digite apenas os números do CELULAR");
formulario.telefone_celular.focus();
return false;
}
if (senha != rep_senha) {
alert("SENHAS não são iguais");
return false;
}
}
<form id="formulario">
<div>PREENCHA OS CAMPOS COM SEUS DADOS REAIS:</div><br/> Nome:
<br/>
<input type="text" id="nome" name="nome"><br/><br/> Email:
<br/>
<input type="text" id="email" name="email" placeholder="exemplo#exemplo.com"><br/><br/> CPF:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente-->
<input type="text" id="cpf" name="cpf" placeholder="000.000.000-00"><br/><br/> Telefone:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente²-->
<input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000"><br/><br/> Celular:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente³-->
<input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000"><br/><br/><br/>
<div>ESCOLHA SEU LOGIN E SUA SENHA:</div><br/> Login:
<br/>
<input type="text" id="login" name="login"><br/><br/> Senha:
<br/>
<input type="password" id="senha" name="senha"><br/><br/> Repetir Senha:<br/>
<input type="password" id="rep_senha" name="rep_senha"><br/><br/><br/>
<input type="submit" value="Enviar" onclick="return validar()">
<input type="reset" value="Limpar" name="limpar">
</form>
misspelled length
misspelled fixo
missed .length on phone numbers
you need to attach to the submit handler and use preventDefault if error
function validar(e) {
var formulario = this;
var nome = formulario.nome.value;
var email = formulario.email.value;
var cpf = formulario.cpf.value;
var telefone_fixo = formulario.telefone_fixo.value;
var telefone_celular = formulario.telefone_celular.value;
var login = formulario.login.value;
var senha = formulario.senha.value;
var rep_senha = formulario.rep_senha.value;
var error = false
if (nome == "") {
alert("Preencha o campo com seu NOME");
formulario.nome.focus();
error = true;
}
if (!error && nome.lenght < 5) {
alert("Digite seu NOME COMPLETO");
formulario.nome.focus();
error = true;
}
if (!error && cpf.length < 11) {
alert("Digite apenas os números do CPF");
formulario.cpf.focus();
error = true;
}
if (!error && telefone_fixo.length < 10) {
alert("Digite apenas os números do TELEFONE");
formulario.telefone_fixo.focus();
error = true;
}
if (!error && telefone_celular.length < 11) {
alert("Digite apenas os números do CELULAR");
formulario.telefone_celular.focus();
error = true;
}
if (!error && senha != rep_senha) {
alert("SENHAS não são iguais");
error = true;
}
if (error) e.preventDefault();
}
window.addEventListener("load",function() {
document.getElementById("formulario").addEventListener("submit",validar);
})
<form id="formulario">
<div>PREENCHA OS CAMPOS COM SEUS DADOS REAIS:</div><br/> Nome:
<br/>
<input type="text" id="nome" name="nome"><br/><br/> Email:
<br/>
<input type="text" id="email" name="email" placeholder="exemplo#exemplo.com"><br/><br/> CPF:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente-->
<input type="text" id="cpf" name="cpf" placeholder="000.000.000-00"><br/><br/> Telefone:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente²-->
<input type="text" id="telefone_fixo" name="telefone_fixo" placeholder="(00) 0000-0000"><br/><br/> Celular:
<font size="1">(Digite apenas números)</font><br/>
<!--Função de CSS invadindo o HTML provisoriamente³-->
<input type="text" id="telefone_celular" name="telefone_celular" placeholder="(00) 00000-0000"><br/><br/><br/>
<div>ESCOLHA SEU LOGIN E SUA SENHA:</div><br/> Login:
<br/>
<input type="text" id="login" name="login"><br/><br/> Senha:
<br/>
<input type="password" id="senha" name="senha"><br/><br/> Repetir Senha:<br/>
<input type="password" id="rep_senha" name="rep_senha"><br/><br/><br/>
<input type="submit" value="Enviar">
<input type="reset" value="Limpar" name="limpar">
</form>
Hello Everyone I want to make sure that in my project once I change the value of a radio button next to it is created / or a textBox is made visible ..
If the radioButton is "(SI)" the textBox is shown
if the radioButton is "(NO") the textBox is dimmed
I am attaching an attempt that I made to generate textBox .. but I do not know how to manage the value of the radioButton ..
PS do not be ruthless, I'm a beginner with JavaScript--
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
var num=1;
function accoda(){
if(document.createElement && document.getElementById && document.getElementsByTagName) {
// crea elementi
var oTr=document.createElement("TR");
var oTd1=document.createElement("TD");
var oTd2=document.createElement("TD");
var oField=document.createElement("INPUT");
var oButt=document.createElement("INPUT");
// setta attributi
oField.setAttribute("type","text");
oField.setAttribute("name","testo"+num);
oButt.setAttribute("type","button");
oButt.setAttribute("value","rimuovi");
// setta gestore evento
if(oButt.attachEvent) oButt.attachEvent('onclick',function(e){rimuovi(e);})
else if(oButt.addEventListener) oButt.addEventListener('click',function(e){rimuovi(e);},false)
// appendi al relativo padre
oTd1.appendChild(oField);
oTd2.appendChild(oButt);
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
document.getElementById('tabella').getElementsByTagName('TBODY')[0].appendChild(oTr);
// incrementa variabile globale
num++
}
}
function rimuovi(e){
if(document.removeChild && document.getElementById && document.getElementsByTagName) {
if(!e) e=window.event;
var srg=(e.target)?e.target:e.srcElement;
// risali al tr del td che contiene l' elemento che ha scatenato l' evento
while(srg.tagName!="TR"){srg=(srg.parentNode)?srg.parentNode:srg.parentElement}
// riferimento al tbody
var tb=document.getElementById('tabella').getElementsByTagName('TBODY')[0];
// rimuovi
tb.removeChild(srg);
}
}
//-->
</script>
</head>
<body>
<form name="modulo">
<input type="button" value="accoda" onclick="accoda()" />
<table border="1" id="tabella">
<tbody>
<tr>
<td><input type="text" name="testo0" /></td><td><input type="button" disabled="disabled" value="rimuovi" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<html>
<body>
<script language="javascript">
function controlla(){
x=document.prova;
if (x.scelta.value=="si"){
window.location.href = '../affidatario.php?idCantiere=<?php echo $idCantiere?>'
return false;
}
if (x.scelta.value=="no"){
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
</script>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br />
NO<input type="radio" name="scelta" value="no" /><br />
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>
Try this
function controlla() {
console.log("oie");
x = document.prova;
if (x.scelta.value == "si") {
window.location.href = '../affidatario.php?idCantiere=608675750'
return false;
}
if (x.scelta.value == "no") {
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
document.querySelectorAll('input[name="scelta"').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
<html>
<body>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si">
<input type="text" id="myInput" style="display: block;"><br>
NO<input type="radio" name="scelta" value="no"><br>
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>
Change the display to 'none' for the textbox
You could have an if block. Something like
if(document.querySelector('_radiobutton_').checked) { //selecting the radio button with "SI"
document.querySelector('theTextBox').style.display = '' //selecting the textbox
}
Here is a simple example:
let chbxElement = document.getElementById('chckbx');
let textBoxElement = document.getElementById('txtbx');
chbxElement.addEventListener('change', (e) => {
textBoxElement.style.display = e.target.checked ? 'block' : 'none';
});
<input type="checkbox" id="chckbx"/>
<input type="text" id="txtbx" hidden/>
Apart from the placement of the textbox, you could add a textbox with for example an id "myInput" and a default display:none;
Then add an eventlistener to the change event. Then according to the value of the radio button show or hide the textbox.
For example:
document.querySelectorAll('input[name="scelta"]').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
var num = 1;
function accoda() {
if (document.createElement && document.getElementById && document.getElementsByTagName) {
// crea elementi
var oTr = document.createElement("TR");
var oTd1 = document.createElement("TD");
var oTd2 = document.createElement("TD");
var oField = document.createElement("INPUT");
var oButt = document.createElement("INPUT");
// setta attributi
oField.setAttribute("type", "text");
oField.setAttribute("name", "testo" + num);
oButt.setAttribute("type", "button");
oButt.setAttribute("value", "rimuovi");
// setta gestore evento
if (oButt.attachEvent) oButt.attachEvent('onclick', function(e) {
rimuovi(e);
})
else if (oButt.addEventListener) oButt.addEventListener('click', function(e) {
rimuovi(e);
}, false)
// appendi al relativo padre
oTd1.appendChild(oField);
oTd2.appendChild(oButt);
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
document.getElementById('tabella').getElementsByTagName('TBODY')[0].appendChild(oTr);
// incrementa variabile globale
num++
}
}
function rimuovi(e) {
if (document.removeChild && document.getElementById && document.getElementsByTagName) {
if (!e) e = window.event;
var srg = (e.target) ? e.target : e.srcElement;
// risali al tr del td che contiene l' elemento che ha scatenato l' evento
while (srg.tagName != "TR") {
srg = (srg.parentNode) ? srg.parentNode : srg.parentElement
}
// riferimento al tbody
var tb = document.getElementById('tabella').getElementsByTagName('TBODY')[0];
// rimuovi
tb.removeChild(srg);
}
}
//-->
</script>
</head>
<body>
<form name="modulo">
<input type="button" value="accoda" onclick="accoda()" />
<table border="1" id="tabella">
<tbody>
<tr>
<td><input type="text" name="testo0" /></td>
<td><input type="button" disabled="disabled" value="rimuovi" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<html>
<body>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br /> NO
<input type="radio" name="scelta" value="no" /><br />
<input type="text" id="myInput" style="display: none;">
<button type="submit">INVIA</button>
</form>
</fieldset>
<script language="javascript">
function controlla() {
x = document.prova;
if (x.scelta.value == "si") {
window.location.href = '../affidatario.php?idCantiere=<?php echo $idCantiere?>'
return false;
}
if (x.scelta.value == "no") {
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
document.querySelectorAll('input[name="scelta"]').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
</script>
</body>
</html>
I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Anyone knows what is wrong here?
Keep getting 500 Internal Server Error. -
"NetworkError: 500 Internal Server Error - http:// sitename /validationengine.php"
Somehow I guess it's something wrong with the php-code. Everything with the validation works until it's time for the send.
HTML
<form id="competition_form" accept-charset="UTF-8" enctype="multipart/form-data" method="post" name="val_form" action="validationengine.php">
<fieldset>
<div id="page1_form" class="pages_form">
<p>Line1</p><br>
<input type="checkbox" name="quest" class="quest_group" value="1"><span class="nr_checkboxes">1. </span>
<label for="quest">labeltext 1</label><br>
<input type="checkbox" name="quest" class="quest_group" value="x"><span class="nr_checkboxes">X. </span>
<label for="quest">labeltext X</label><br>
<input type="checkbox" name="quest" class="quest_group" value="2"><span class="nr_checkboxes">2. </span>
<label for="quest">labeltext 2</label><br>
<p>Text</p>
<textarea name="motivering" rows="4" cols="66" maxlength="100"></textarea>
</div>
<div id="page2_form" class="pages_form">
<input type="checkbox" name="prize_check" value="win 1">
<label for="prize_check">Win 1</label><br>
<input type="checkbox" name="prize_check" value="win 2">
<label for="prize_check">Win 2</label><br>
<div class="full_input input_blocks">
<label for="namn">Namn:</label>
<input type="text" name="namn" maxlength="100" value="" />
<span id="namn_error" class="error">Du måste skriva in ditt namn.</span>
</div>
<div class="full_input input_blocks">
<label for="adress">Adress:</label>
<input type="text" name="adress" maxlength="100" value="" />
<span id="adress_error" class="error">Du måste skriva in din adress.</span>
</div>
<div class="half_input input_blocks">
<label for="postnr">Postnr:</label>
<input type="text" name="postnr" maxlength="50" value="" />
<span id="postnr_error" class="error">Du måste skriva in ditt postnummer.</span>
</div>
<div class="half_input input_blocks">
<label for="ort">Ort:</label>
<input type="text" name="ort" maxlength="50" value="" />
<span id="ort_error" class="error">Du måste skriva in din bostadsort.</span>
</div>
<div class="half_input input_blocks">
<label for="email">Mejl:</label>
<input type="text" name="email" maxlength="50" value="" />
<span id="email_error" class="error">Du måste skriva in din mejl-adress.</span>
</div>
<div class="half_input input_blocks">
<label for="mobil">Mobil:</label>
<input type="text" name="mobil" maxlength="50" value="" />
<span id="mobil_error" class="error">Du måste skriva in ditt telefonnummer</span>
</div>
<div id="rules_box">
<input type="checkbox" name="rules_check" value="Tävlingsvillkor godkända">
<label for="rules_check">Jag har läst och godkänner <b>tävlingsvillkoren</b></label><br>
<span id="rules_error" class="error">Du måste godkänna tävlingsvillkoren för att tävla.</span>
</div>
<input type="submit" name="submit" value="" class="submit-button" id="submit_btn" />
</div>
</fieldset>
</form>
JS
$(function() {
$('.error').hide();
$("input[name='email']").onchange=function(){$('.error').hide();};
$("input[name='email']").click(function() {
$('.error').hide();
});
$(".submit-button").click(function() {
var form = $('#competition_form');
var name = $("input[name='namn']").val();
var adress = $("input[name='adress']").val();
var postnr = $("input[name='postnr']").val();
var ort = $("input[name='ort']").val();
var email = $("input[name='email']").val();
var mobil = $("input[name='mobil']").val();
var rules = $("input[name='rules_check']").is(':checked');
$('.error').hide();
if (name == "") {
$("#namn_error").show();
return false;
}
if (adress == "") {
$("#adress_error").show();
return false;
}
if (postnr == "") {
$("#postnr_error").show();
return false;
}
if (ort == "") {
$("#ort_error").show();
return false;
}
if (email == "" || !isValidEmailAddress( email ) ) {
$("#email_error").show();
return false;
}
if (mobil == "") {
$("#mobil_error").show();
return false;
}
console.log(rules);
if (!rules) {
$("#rules_error").show();
return false;
}
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType:'html',
success: function(data) {
$('#thankyou_pop').fadeIn(500);
},
error: function(data) {
//AJAX request not completed
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
PHP
<?php
if( isset($_POST) ){
// validation
$validationOK=true;
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
$EmailTo = "example#example.com";
$Subject = "Nytt Tävlingsbidrag";
$quest = "";
if (isset($_POST['quest'])) {
$answer = Trim(stripslashes($_POST['quest']));
if($answer == 1) {
$quest = "Rätt svar";
} else {
$quest = "Fel svar";
}
}
if($quest == "") {
$quest = "Inget svar";
}
$motivering = Trim(stripslashes($_POST['motivering']));
if ($motivering == "") {
$motivering = "Ingen motivering";
}
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald"
} else {
$vinst = $win_answer;
}
}
$namn = Trim(stripslashes($_POST['namn']));
$adress = Trim(stripslashes($_POST['adress']));
$postnr = Trim(stripslashes($_POST['postnr']));
$ort = Trim(stripslashes($_POST['ort']));
$Email = Trim(stripslashes($_POST['email']));
$mobil = Trim(stripslashes($_POST['mobil']));
$villkor = Trim(stripslashes($_POST['rules_check']));
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
} else {
// prepare email body text
$headers = "Berocca Boost Tävlingsbidrag" . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$Body = "<h3>Nytt Tävlingsbidrag</h3>
<p><strong>Fråga: </strong> {$quest} </p>
<p><strong>Motivering: </strong> {$motivering} </p>
<p><strong>Föredragen vinst: </strong> {$vinst} </p>
<p><strong>Namn: </strong> {$namn} </p>
<p><strong>Adress: </strong> {$adress} </p>
<p><strong>Postnr: </strong> {$postnr} </p>
<p><strong>Ort: </strong> {$ort} </p>
<p><strong>E-mail: </strong> {$Email} </p>
<p><strong>Mobil: </strong> {$mobil} </p>
<p><strong>Villkor accepterade: </strong> {$villkor} </p>
<br>
<p>IP address: {$ipaddress} Date: {$date} Time: {$time}</p>";
// send email
mail($EmailTo, $Subject, $Body, $headers);
}
}
?>
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald" //<====== (Missing semi-colon ";")
} else {
$vinst = $win_answer;
}
}
You have made a typo error. Missed a semicolon.
if ($win_answer == "")
{
$vinst = "Ingen vinst vald"
^^^ // Missing semicolon
}
else
{
$vinst = $win_answer;
}