Home > Web Front-end > JS Tutorial > How to verify the correct email address in JS

How to verify the correct email address in JS

php中世界最好的语言
Release: 2018-04-28 09:35:03
Original
4280 people have browsed it

This time I will show you how to verify the correct email address in JS. What are the precautions for verifying the correct email address in JS? 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 the correct email address in JS

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

How to verify the correct email address in 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:

controller receives js and passes json parameters

js implements front-end and back-end Json transmission to each other

The above is the detailed content of How to verify the correct email address in 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