我想知道如何只允許 @gmail.com 和 @yahoo.com 用于我的 html 電子郵件驗證。我知道 <input type="email" 驗證,但這將允許任何格式的電子郵件,我只希望接受這兩個。我該怎么做??
uj5u.com熱心網友回復:
唯一的方法是 RegExp
- 如果您使用框架(angular/react/vue),他們有自己的(兼容的第三方)庫來處理表單驗證。
- 如果您使用普通 JS,您可以在輸入中添加 onchange 事件并使用所需的正則運算式測驗輸入,或者在提交表單之前您可以測驗輸入。
您將需要的正則運算式
/^[az][a-z0-9_.]*@(gmail|yahoo).com$/gm
有關使用 Javascript 的正則運算式的更多資訊:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
uj5u.com熱心網友回復:
好的,這不是實作這一點的最佳方式,最好的方式是在后端使用它,使用 PHP 電子郵件驗證過濾器。
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/css/master.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<form id="emailForm" action="" method="post">
<label for="email">E-mail</label><br>
<input id="email" type="email" name="email" placeholder="Please enter your
email" value="">
<button onclick="validate();" type="button" name="button">Submit</button>
</form>
</body>
</html>
Inline javascript,你可以稍后攜帶它,將其保存在html下以進行測驗。
<script type="text/javascript">
function validate(){
var email = $('#email').val();
if (email.length == 0) {
window.alert("you didn't enter an email");
}
if (!email.includes('@')) {
window.alert("you mail is unvalid");
}
var emailHost = email.substr((-1)*(email.length - email.indexOf('@') - 1));
var allowedDomains = ["gmail.com","hotmail.com","yahoo.com"];
var inAllowed = false;
for(i=0;i<allowedDomains.length;i ){
if (allowedDomains[i] == emailHost) {
inAllowed = true;
}
}
if (!inAllowed) {
window.alert("your e-mail hosting not supported");
}else { //submit form here
window.alert("success");
$('#emailForm').submit();
}
}
</script>
如果使用 php,后端從 $_POST 獲取電子郵件
<?php
var_dump($_POST);
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347465.html
上一篇:我的androidstudio代碼構建成功但輸出應用程式崩潰
下一篇:在React中驗證字串陣列
