简体   繁体   English

email 验证在 javascript 中不起作用?

[英]email validation is not working in javascript?

I have for a frontendmentorchallenge tried to do email validation for webpage.我有一个前端挑战尝试对网页进行 email 验证。 I have made a validation function to display error message when there is wrong email id entered.我进行了验证 function 以在输入错误的 email id 时显示错误消息。 But it isn't working.但它不起作用。 I have given the html and JavaScript我已经给出了 html 和 JavaScript

 function validate() { var email = document.getElementById("email").value; var reg = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; var result = reg.test(email); if (result == false) { alert("sorry"); return false; } return true; }
 <form action="#" method="post" onsubmit="return validate()"> <div class="inputgrp"> <input type="text" placeholder="Email Address" id="email"> <img src="/images/icon-error.svg" alt="" class="error"> <button type="submit"><img src="/images/icon-arrow.svg " ></button> <div class="errormsg"> <small>please provide a valid Email</small> </div> </div> </form>

To create a regex use创建正则表达式使用

 var reg = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

you have created only a string, and there is no test method on string您只创建了一个字符串,并且在字符串上没有测试方法

such as

var reg= /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var result= reg.test("abcd@gmail.com");
console.log(result)
// VM1103:3 true

My problem has been resolved.我的问题已经解决了。 The problem is i created a string instead of creating regX.问题是我创建了一个字符串而不是创建 regX。

So i changed var reg = "^\w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$";所以我改变了 var reg = "^\w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$"; to the correct format as正确的格式为

var reg = /^\w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/; var reg = /^\w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/;

Thanks for those who answered my question.I posting this answer because in future it might be helpful to somebody感谢那些回答我问题的人。我发布这个答案是因为将来它可能对某人有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM