js中通过正则表达式验证邮箱是否合法

1、效果展示

在这里插入图片描述
在这里插入图片描述

2、问题描述

当用户在输入框输入邮箱后、点击验证邮箱按钮。系统给出提示信息。

3、代码实现

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		
		<script type="text/javascript">
			
			window.onload=function(){
				
				var check=document.getElementById("btn").onclick=function(){
					var email=document.getElementById("email").value;//获取输入的字符串
					var emailRegExp=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;//验证邮箱的正则表达式
					var ok=emailRegExp.test(email);//验证是否符合要求
					
					if(ok){
						document.getElementById("erroremail").innerText="输入的格式符合要求";
					}else{
						document.getElementById("erroremail").innerText="输入的格式不符合要求!!!";
					}
					
				}
				
				document.getElementById("email").onfocus=function(){
					document.getElementById("erroremail").innerText="";
				}
				
			}
			
			
		</script>
		
		
		
		<input type="text" id="email" />
		<span id="erroremail" style=" font: 12px; color: red;"></span>
		<br />
		<input type="button" value="验证邮箱" id="btn" />
		
	</body>
</html>

posted on 2022-08-28 22:17  热爱技术的小郑  阅读(265)  评论(0)    收藏  举报