请问有人能告诉我如何改进这段代码,最重要的是将我的电子邮件验证排序,以便在 Z 不等于空或字符串“Email”时在所有情况下正常工作。
所有字段都已经以适当的措辞开始,作为向客户展示的示例。
提前致谢。
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;
}
}
}
alert(z)
来查看它的值吗? - DevlshOnex,y,z
。b)纠正您的缩进。c)保持您的代码DRY:创建一个函数来检查null
,""
或给定值(例如“名称”,“电子邮件”,“电话号码”)。 - ComFreek