[英]javascript email validation , can't get indexOf work
here is my html code: 这是我的html代码:
<input id="email" placeholder="Enter your email" type="email" required>
<button type="submit" id="submitButton">SUBMIT</button>
js code: js代码:
var email = document.getElementById('email');
var submitButton = document.getElementById('submitButton');
submitButton.onclick = function(){
if(email.value == "")
alert("Please enter correct email");
return false;
if(email.indexOf("@") < 1 || email.lastIndexOf(".") - email.indexOf("@") <2)
alert("Please enter correct email");
return false;
else
return(true);
The error message always the same : TypeError: email.indexOf is not a function at HTMLButtonElement.submitButton.onclick 错误消息始终相同:TypeError:email.indexOf不是HTMLButtonElement.submitButton.onclick上的函数
You need the value of the input element. 您需要输入元素的值。 email = document.getElementById('email')
will return the input element but not it's value email = document.getElementById('email')
将返回输入元素,但不是它的值
Make this change 进行更改
var email = document.getElementById('email').value
; var email = document.getElementById('email').value
;
If you want to check for email. 如果您要检查电子邮件。 Its easier to use regex to do so. 使用正则表达式更容易做到这一点。 See example below on how to do it. 请参阅下面的示例以了解操作方法。
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
It uses basic regex that a lot of resources reference for checking type of email. 它使用许多资源参考的基本正则表达式来检查电子邮件的类型。
function validateEmail(email) { var re = /^(([^<>()[\\]\\\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\"]+)*)|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validate() { $("#result").text(""); var email = $("#email").val(); if (validateEmail(email)) { $("#result").text(email + " is valid :)"); $("#result").css("color", "green"); } else { $("#result").text(email + " is not valid :("); $("#result").css("color", "red"); } return false; } $("#validate").bind("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <p>Enter an email address:</p> <input id='email'> <button type='submit' id='validate'>Validate!</button> </form> <h2 id='result'></h2>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.