Can anyone please tell me how I can improve this code, and most importantly sort my Email validation to work in all cases where Z does not either equal nothing or string "Email"
All fields start with appropriate wording already entered as an example to customers.
Kind regards in advance.
function validateForm()
{
//Uses HTML field IDs
var x=document.forms["myForm"]["name"].value;
var y=document.forms["myForm"]["phone"].value;
var z=document.forms["myForm"]["email"].value;
//Name locator
if (x==null || x=="" || x=="Name")
{
alert("Please enter the your name.");
return false;
}
//Contact method locator
if ((y==null || y=="" || y=="Phone Number")&&(z==null || z=="" || z=="Email"))
{
alert("Please enter a contact method.");
return false;
}
//Phone numeric validation, this runs if Email field is not edited
if (z==null || z=="" || z=="Email")
{
if (isNaN(y)||x.indexOf(" ")!=-1)
{
alert("Telephone must be a numeric value.");
return false;
}
}
//Phone length validation, this runs if Email field is not edited
if (z==null || z=="" || z=="Email")
{
if (y.length > 14)
{
alert("Telephone must be valid.");
return false;
}
}
//Email validation, does not work, this should run only when something is entered into the field
if (z!=null || z!="" || z!="Email")
{
var atpos=z.indexOf("@");
var dotpos=z.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length)
{
alert("This is not a valid e-mail address");
return false;
}
}
}
You could do a few things.
z==null || z==""
could be replaced with !Boolean(z)
or !z
z!=null || z!=""
could be replaced with Boolean(z)
or !!z
You should also try to always use === instead of == unless your expecting type coercion.
So your check for z == "Email"
could change to something like this z.toLowerCase() === "email"
It also seems like you repeat code --> z==null || z=="" || z=="Email"
(x2). You could combine Phone numeric validation and Phone length validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With