如何在jQuery中验证Email Id
jQuery是一个最快的轻量级JavaScript库,用于简化HTML/CSS文档,或者更准确地说,文档对象模型(DOM)和JavaScript之间的交互。
jQuery因其 “少写多做 “的格言而广为人知。它的意思很简单,就是你只需要写几行代码就可以达到你的目的。
方法:你可以使用jQuery的regex模式来验证电子邮件。雷格斯表达式是用于搜索操作的,它们是代表要匹配的模式的特殊字符串。
示例:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<style>
body {
text-align: center;
}
.contactform-buttons {
background-color: #4CAF50;
/* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
</style>
<script>
(document).ready(function () {
('.error').hide();
('#submit').click(function () {
var name =('#name').val();
var email = ('#email').val();
if (name == '') {
('#name').next().show();
return false;
}
if (email == '') {
('#email').next().show();
return false;
}
if (IsEmail(email) == false) {
('#invalid_email').show();
return false;
}
.post("",("#myform").serialize(),
function (response) {
('#myform').fadeOut('slow', function () {
('#correct').html(response);
('#correct').fadeIn('slow');
});
});
return false;
});
});
function IsEmail(email) {
var regex =
/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+/;
if (!regex.test(email)) {
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<center>
<h1 style="color:green">GeeksforGeeks</h1>
<form action="" method="post" id="contactform">
<label for="name">Name:</label>
<input name="name" id="name" type="text"
placeholder="Please enter your name"
class="contact-input">
<span class="error">
Enter your name here
</span>
<label for="email">Email :</label>
<input name="email" id="email" type="text"
placeholder="Please enter your email"
class="contact-input">
<span class="error">
Enter your email-id here
</span>
<span class="error" id="invalid_email">
Email-id is invalid
</span>
<br /><br />
<input type="submit"
class="contactform-buttons"
id="submit" value="Send" />
<input type="reset"
class="contactform-buttons"
id="" value="Clear" />
</form>
<div id="correct"
style="color:gray;">
</div>
</center>
</body>
</html>
输出: