Home > Web Front-end > JS Tutorial > body text

How to verify email format using JS

php中世界最好的语言
Release: 2018-05-08 11:23:09
Original
2347 people have browsed it

This time I will show you how to use JS to verify the E-mail format, and what are the precautions for using JS to verify the E-mail format. The following is a practical case, let's take a look.

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 @.

1: Code

nbsp;html>


<meta>
<title>利用JavaScript验证是否符合电子邮箱地址</title>

<script>
  // 创建第一个函数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>

  <!-- onsubmit是一个验证表单功能,为true提交, -->
  
Copy after login
    Email:     

2: Result

How to verify email format using JS

The following picture explains The email format you entered is accurate, whether it exists or not is another matter!

How to verify email format using JS

# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for Vue to convert html strings into HTML

$http method steps to pass json parameters Detailed explanation

The above is the detailed content of How to verify email format using JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template