Home >Web Front-end >JS Tutorial >Example sharing of email address format verification in JavaScript
I recently worked on a front-end project, which requires that the input data must contain the @ symbol and the period (.). At the same time, @ cannot be the first character of the email address, and there must be at least one period after @. This article mainly shares with you the E-mail address format verification in JavaScript. The project requires that the input data must contain the @ symbol and the period. The code is simple and easy to understand, I hope it can help everyone.
1: Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>利用JavaScript验证是否符合电子邮箱地址</title> </head> <script type="text/javascript"> // 创建第一个函数validate_emil()并包含两个参数 function validate_email(field, alerttxt) { with (field) { //利用indexOf() 方法返回某个指定的字符串值在字符串中首次出现的位置--定义一个变量apos将第一次出现的“@”赋值给apos apos = value.indexOf("@"); //利用lastIndexOf() 方法返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索-- //stringObject.lastIndexOf(searchvalue,fromindex) //fromindex 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的最后一个字符处开始检索。 dotpos = value.lastIndexOf("."); // 判断符合"@"的位置,或者"."的位置是否在"@"的后面 if (apos < 1 || dotpos - apos < 2) { // 利用alert()弹出一个警告窗来执行alerttxt的操作 // 邮箱地址不符合 alert(alerttxt); return false; } else { // 邮箱地址符合 return true; } } } // 创建第二个函数validate_form()并包含一个参数 function validate_form(thisform) { with (thisform) { if (validate_email(email, "Not a valid e-mail address!") == false) { // 利用focus()将输入焦点移至对象上 email.focus(); return false; } } } </script> <body> <!-- onsubmit是一个验证表单功能,为true提交, --> <form action="submitpage.htm" onsubmit="return validate_form(this);" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>
2: Result
## The picture below shows that the email format you entered is accurate. Whether it exists or not is another matter!
The above is the detailed content of Example sharing of email address format verification in JavaScript. For more information, please follow other related articles on the PHP Chinese website!