This is in reference to the form here.
In a form I am building the client wants the email field to be optional but still, when/if an email is typed in, the form still validates that it is a valid email. Also, the same is wanted for a cell phone number.
I’ve tried to figure this out on my own and can’t seem to do so. I have even gone to Google and nothing helpful comes up.
Here is a link to the form I built: link
Below is the javascript:
// form validation function //
function validate(form) {
var name = form.name.value;
var hphonenumber = form.hphonenumber.value;
var cphonenumber = form.cphonenumber.value;
var email = form.email.value;
var apptdate = form.apptdate.value;
var appttime = form.appttime.value;
var appttype = form.appttype.value;
var nameRegex = /^[a-zA-Z]+(([\\'\\,\\.\\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
var phoneRegex = /^(?:\\([2-9]\\d{2}\\)\\ ?|[2-9]\\d{2}(?:\\-?|\\ ?))[2-9]\\d{2}[- ]?\\d{4}$/;
var emailRegex = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;
var messageRegex = new RegExp(/<\\/?\\w+((\\s+\\w+(\\s*=\\s*(?:".*?"|'.*?'|[^'">\\s]+))?)+\\s*|\\s*)\\/?>/gim);
if(name == "") {
inlineMsg('name','You must enter your name.',2);
return false;
}
if(!name.match(nameRegex)) {
inlineMsg('name','You have entered an invalid name.',2);
return false;
}
if(hphonenumber == "") {
inlineMsg('hphonenumber','<strong>Error</strong><br />You must enter a phone number.',2);
return false;
}
if(!hphonenumber.match(phoneRegex)) {
inlineMsg('hphonenumber','You have entered an invalid phone number.',2);
return false;
}
if(!cphonenumber.match(phoneRegex)) {
inlineMsg('cphonenumber','You have entered an invalid phone number.',2);
return false;
}
if(!email.match(emailRegex)) {
inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',2);
return false;
}
if(apptdate == "") {
inlineMsg('apptdate','<strong>Error</strong><br />You must enter an appointment date.',2);
return false;
}
if(appttime == "") {
inlineMsg('appttime','<strong>Error</strong><br />You must enter an appointment time.',2);
return false;
}
if(appttype == "") {
inlineMsg('appttype','You must enter a reason for your appointment request.');
return false;
}
if(appttype.match(messageRegex)) {
inlineMsg('appttype','You have entered an invalid message.');
return false;
}
return true;
}