I am trying to validate input on an HTML form. I am trying to use one script to validate various forms that have several similar elements. All in all there are about 15 different fields but I am only putting 3. Below works on the form that has all of the elements but fails on any form that does not have a specific field.
if (form.name.value == ""){ // Check if blank
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else if ( !/^\w{10}$/.test( form.phone.value )) { // Check for phone
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; // Submit!
Since this only works if all are present what i want to do is validate only if it exists. I have tried nesting the validation under a statement that should check for the element before trying to validate it and if the element doesn't exist it should move on to the next.
if (document.forms[0].name){ //does field exist?
if (form.name.value === ""){
alert( "\nEnter a name." );
form.name.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else if (document.forms[0].phone){
if ( !/^\w{10}$/.test( form.phone.value )) { user
form.name.style.border=""
alert( "\nEnter a valid phone number!" );
form.phone.focus();
return false; // Stop the form processing.
}
else{
return true; //field ok move on.
}
}
else{
return true; // Submit!
}
Any help help would be appreciated!