Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Not Equal" sign not recognised in Javascript Form Validation

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;
        }
    }
}
like image 400
user2707736 Avatar asked Jan 13 '23 14:01

user2707736


1 Answers

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.

like image 50
vernak2539 Avatar answered Jan 17 '23 09:01

vernak2539