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!
At present you are checking that (document.forms[0].name) is available and then if this is dead it check if (document.forms[0].phone) is true and then…… and then if none are true it resorts to the ‘else’ and returns are true. The use of
if elsemeans that you only bother with anything after if this part has failed.You could try.
As the function is going to return as true anyway, you don’t need to state return true anywhere else (also this will stop the process as it has
returnedand stopped). The only reason to stop the process if things have gone wrong.. hencereturn false;