仅允许使用表单javascript验证提交请求的电子邮件列表

时间:2017-05-25 06:28:16

标签: javascript jquery html ajax css3

我有一个有效用户列表。我希望只有这些用户才能发送帖子请求,所有其他用户都应该被识别为无效用户。我编写了javascript代码但无法让无效用户停止执行程序。



 function validateForm() {
        var x = document.forms["myForm"]["email"].value;
        var atpos = x.indexOf("@");
        var dotpos = x.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
            alert("Not a valid e-mail address");
            return false;
        }
        var eMailList = ["hankev@gmail.com", "slurp@gmail.com", "cofo@gmail.com", "vecrify@gmail.com"];
        var i;
        for (i=0; i< eMailList.length; i++){
    	    if(x != eMailList[i]){
		    alert("Not a valid user");
        	return false;
            }
    
        }
    }
&#13;
 <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
    Email: <input type="text" name="email">
    <input type="submit" value="Submit">
</form>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

首先,如果你关心安全问题,你不应该在javascript方面这样做。

请参阅下面的代码示例:

&#13;
&#13;
function validateForm() {
    var x = document.forms["myForm"]["email"].value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var eMailList = ["hankev@gmail.com", "slurp@gmail.com", "cofo@gmail.com", "vecrify@gmail.com"];
    var i;
	if($.inArray(x,eMailList) == -1)
	{
		alert("Not a valid user");
	}
	else
	{
		alert("valid user");
	}
}
&#13;
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
&#13;
&#13;
&#13;

链接到JsFiddle

答案 1 :(得分:0)

无需循环遍历数组,只需使用下面实现的if(eMailList.indexOf(x) < 0)即可。您的代码始终返回false的原因是因为即使您输入有效的电子邮件,它也不等于数组中的每个其他项。

 function validateForm() {
        var x = document.forms["myForm"]["email"].value;
        var atpos = x.indexOf("@");
        var dotpos = x.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
            alert("Not a valid e-mail address");
            return false;
        }
        var eMailList = ["hankev@gmail.com", "slurp@gmail.com", "cofo@gmail.com", "vecrify@gmail.com"];

        if(eMailList.indexOf(x) < 0){
		    alert("Not a valid user");
        	return false;
        }
    }
 <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm();" method="post">
    Email: <input type="text" name="email">
    <input type="submit" value="Submit">
</form>