[英]how to validate email in javascript
I am working on a mvc 5 project .in contact us page I want user to send admin his / her emaiul address .so I want to validate email in javascript on that page .I wrote some code that does not work properly.我正在开发一个 mvc 5 项目。在联系我们页面中,我希望用户向管理员发送他/她的电子邮件地址。所以我想在该页面上的 javascript 中验证电子邮件。我编写了一些无法正常工作的代码。 I want you to help me plesae.我要你帮我请。
<script language="javascript">
function f1() {
var inputText = document.getElementById("email").value;
var mailformat = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.value.match(mailformat)) {
document.form1.text1.focus();
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
function validateEmail(email) {
var re = ([\w-+]+(?:\.[\w-+]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7});
return re.test(email);
}
A basic HTML and JS working code for validating email with JS is given here for u-此处为您提供了用于使用 JS 验证电子邮件的基本 HTML 和 JS 工作代码-
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; } else { alert("Valid e-mail address"); return true; } }
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="Submit"> </form>
Think, u have your answer :)想想,你有你的答案:)
<form name="form" action="#" onSubmit="return f1()" method="POST">
<input type="email">
</form>
<script>
function f1(){
var email = document.forms["form"]["Email"].value;
var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)@([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
if(!regex.test(email)){
alert("You have entered an invalid email address!");
return false;
}
}
</script>
You don't want inputText.value
only inputText
like this你不希望inputText.value
只有inputText
这样
<input type="text" id="email" /> <input type="submit" onClick="f1()"/> <script language="javascript"> function f1() { console.log(document.getElementById("email").value); var inputText = document.getElementById("email").value; console.log(inputText) var mailformat = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/; if (inputText.match(mailformat)) { // <<<<<<< here //document.form1.text1.focus(); alert("correct") } else { alert("You have entered an invalid email address!"); document.form1.text1.focus(); event.preventDefault(); } } </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.