RisTar
07-28-2009, 12:55 AM
Hi, im trying to validate a form using javascript.
If there are errors in the form javascript lists them in a div tag
on the top of the page. the problem is that whenever i click
the submit for the first time everything is working but after
i get the errors if im clicking submit again, it's submitting the form
regardless of the errors...
Attached is the code
Thanks
window.onload = initForm;
var valid = true;
var errorlog = new Array();
function initForm(){
document.forms[0].onsubmit = validateForm;
}
function validateForm(){
// validate first name
if (document.getElementById("firstname").value == ""){
errorlog[0] = true;
}
// validate last name
if (document.getElementById("lastname").value == ""){
errorlog[1] = true;
}
// validate phone number
if (document.getElementById("tel").value == "" ||
document.getElementById("tel").value.search(/^\d{10}$/) == -1 &&
document.getElementById("tel").value.search(/^\d{8}$/) ==-1 ){
errorlog[2] = true;
}
notValid();
return valid;
}
function changeId(){
document.getElementById("tobechanged").id = "errorlog";
}
function outputErrors(){
if (errorlog[0]){
document.getElementById("errorlog").innerHTML += "Please enter your first name." + "<br/>";
}
if (errorlog[1]){
document.getElementById("errorlog").innerHTML += "Please enter your last name." + "<br/>";
}
if (errorlog[2]){
document.getElementById("errorlog").innerHTML += "Please enter a valid phone number." + "<br/>";
}
}
function notValid(){
changeId();
outputErrors();
valid = false;
}
If there are errors in the form javascript lists them in a div tag
on the top of the page. the problem is that whenever i click
the submit for the first time everything is working but after
i get the errors if im clicking submit again, it's submitting the form
regardless of the errors...
Attached is the code
Thanks
window.onload = initForm;
var valid = true;
var errorlog = new Array();
function initForm(){
document.forms[0].onsubmit = validateForm;
}
function validateForm(){
// validate first name
if (document.getElementById("firstname").value == ""){
errorlog[0] = true;
}
// validate last name
if (document.getElementById("lastname").value == ""){
errorlog[1] = true;
}
// validate phone number
if (document.getElementById("tel").value == "" ||
document.getElementById("tel").value.search(/^\d{10}$/) == -1 &&
document.getElementById("tel").value.search(/^\d{8}$/) ==-1 ){
errorlog[2] = true;
}
notValid();
return valid;
}
function changeId(){
document.getElementById("tobechanged").id = "errorlog";
}
function outputErrors(){
if (errorlog[0]){
document.getElementById("errorlog").innerHTML += "Please enter your first name." + "<br/>";
}
if (errorlog[1]){
document.getElementById("errorlog").innerHTML += "Please enter your last name." + "<br/>";
}
if (errorlog[2]){
document.getElementById("errorlog").innerHTML += "Please enter a valid phone number." + "<br/>";
}
}
function notValid(){
changeId();
outputErrors();
valid = false;
}