search
HomeWeb Front-endJS TutorialTwo implementation methods of JavaScript form validation

The example of this article shares the implementation method of js form verification for your reference. The specific content is as follows

First type: js form verification

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>注册-个人用户</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <script src="//cdn.bootcss.com/jquery/3.0.0-beta1/jquery.js"></script>
  <style>
    body {
      font-family: Arial, "宋体", Lucida, Verdana, Helvetica, sans-serif;
      font-size: 12px;
      color: #333;
      line-height: 150%;
      background: #f2f2f2;
    }

    .hide{display:none;}

    .focus,.error {
      color: #e4393c;
      line-height: 36px;
      height: 36px;
      position: absolute;
      top: 0px;

      width: 260px;
      padding: 0 5px;
      background: #FFEBEB;
      border: 1px solid #ffbdbe;
    }

    .error span,.focus span {
      padding: 5px 0;
      line-height: 13px;
      display: block;
    }

    .focus {
      color: #666;
      width: 260px;;
      line-height: 36px;
      background: #f7f7f7;
      border: 1px solid #dddddd;
    }

    .regist {
      width: 990px;
      padding: 0;
      margin: 0 auto;
      zoom: 1;
    }


    .mc {
      padding: 30px 0 20px;
      border: solid #dddddd; border-width : 0px 1px 1px;
      background: #FFF;
      overflow: hidden;
      zoom: 1;
      border-width: 0px 1px 1px;
    }

    .form {
      float: left;
      width: 750px;
      font-size: 12px;
    }

    .form label,.form input,.form select,.form textarea,.form button,.form .label {
      float: left;
      font-size: 12px;
    }

    .item {
      padding-top: 9px;
      height: 60px;
      line-height: 34px;
      position: relative;
      z-index: 1;
    }

    .label {
      float: left;
      width: 190px;
      text-align: right;
      font-size: 14px;
      color: #999;
      padding-right: 10px;
    }

    .input {
      float: left;
      position: relative;
      width: 270px;
      overflow: visible;
    }

    .text {
      float: none;
      width: 275px;
      height: 37px;
      line-height: 32px;
      border: 1px solid #cccccc;
      font-size: 14px;
      font-family: arial, "宋体";
      overflow: hidden;
    }

  </style>
</head>
<body>
  <p class="regist"> 
    <p class="mc">
      <form id="personRegForm" class="form" action="login.html" method="POST" onsubmit="return validateForm();">
        <p class="item">
          <span class="label">用户名:</span>
          <p class="input">
            <input type="text" id="username" name="username" class="text">

            <label id="username_msg" class="hide"></label>
          </p>
        </p>
        <p class="item">
          <span class="label">请设置密码:</span>
          <p class="input">
            <input type="password" id="password" name="password" class="text">

            <label id="pwd_msg" class="hide"></label>
          </p>
        </p>
        <p class="item">
          <span class="label">请确认密码:</span>
          <p class="input">
            <input type="password" id="pwdRepeat" name="pwdRepeat" class="text">

            <label id="pwdRepeat_msg" class="hide"></label>
          </p>
        </p>
        <p class="item">
          <span class="label">验证邮箱:</span>
          <p class="input">
            <input type="text" id="mail" name="mail" class="text">

            <label id="mail_msg" class="hide"></label>
          </p>
        </p>
        <p class="item">
          <span class="label"> </span>
          <input type="submit" class="btn-img" id="registsubmit" value="立即注册" />
        </p>
      </form>
    </p>  
  </p>


   <script>
    window.onload = function(){
      // 1. 用户名
      $("#username").focus(function(){
        /* 获取焦点
        var username_msg = $("#username_msg");
        username_msg.text("4-20位字符,支持英文、数字及&#39;-&#39;、&#39;_&#39;组合");
        username_msg.attr("class","focus");
        */
        elemFocus("username_msg","4-20位字符,支持英文、数字及&#39;-&#39;、&#39;_&#39;组合");

      }).blur(userValidator);
      // 2. 密码
      $("#password").focus(function(){
        elemFocus("pwd_msg","6-20位字符,可使用字母、数字的组合");
      }).blur(pwdValidator);
      // 3. 确认密码
      $("#pwdRepeat").focus(function(){
        elemFocus("pwdRepeat_msg","6-20位字符,可使用字母、数字的组合");
      }).blur(pwdRepeatValidator);
      // 4. Email
      $("#mail").focus(function(){
        elemFocus("mail_msg","完成验证后,可以使用该邮箱登录和找回密码");
      }).blur(emailValidator);
    }

    // 定义函数 - 通用的信息提示
    function elemFocus(eleId,text){
      var ele_msg = $("#"+eleId);
      ele_msg.text(text);
      ele_msg.attr("class","focus");
    }

    // 定义验证用户名的函数
    function userValidator(){
      // 获取用户名输入的值
      var value = $("#username").val();
      // 获取用于显示提示信息的元素
      var username_msg = $("#username_msg");
      // 验证逻辑
      if(value==""||value==null){
        username_msg.text("用户名不能为空");
        username_msg.attr("class","error");
        return false;
      }else if(value.length<4||value.length>20){
        username_msg.text("用户名的长度不正确");
        username_msg.attr("class","error");
        return false;
      }else if(!/^[a-zA-Z0-9-_]{4,20}$/.test(value)){
        username_msg.text("用户名输入不正确");
        username_msg.attr("class","error");
        return false;
      }
      // 验证通过修改正确样式
      if(!username_msg.hasClass("hide")){
        username_msg.text("");
        username_msg.attr("class","hide");
      }
      return true;
    }
    // 定义验证密码的函数
    function pwdValidator(){
      var value = $("#password").val();
      var pwd_msg = $("#pwd_msg");
      if(value==""||value==null){
        pwd_msg.text("密码不能为空");
        pwd_msg.attr("class","error");
        return false;
      }else if(value.length<6||value.length>20){
        pwd_msg.text("密码的长度不正确");
        pwd_msg.attr("class","error");
        return false;
      }else if(!/^[a-zA-Z0-9]{6,20}$/.test(value)){
        pwd_msg.text("密码输入不正确");
        pwd_msg.attr("class","error");
        return false;
      }
      if(!pwd_msg.hasClass("hide")){
        pwd_msg.text("");
        pwd_msg.attr("class","hide");
      }
      return true;
    }
    // 定义确认密码验证的函数
    function pwdRepeatValidator(){
      var value = $("#pwdRepeat").val();
      var pwdRepeat_msg = $("#pwdRepeat_msg");
      var pwd = $("#password").val();
      if(value==""||value==null){
        pwdRepeat_msg.text("密码不能为空");
        pwdRepeat_msg.attr("class","error");
        return false;
      }else if(value.length<6||value.length>20){
        pwdRepeat_msg.text("密码的长度不正确");
        pwdRepeat_msg.attr("class","error");
        return false;
      }else if(!/^[a-zA-Z0-9]{6,20}$/.test(value)){
        pwdRepeat_msg.text("密码输入不正确");
        pwdRepeat_msg.attr("class","error");
        return false;
      }else if(value != pwd){
        pwdRepeat_msg.text("两次密码输入不一致");
        pwdRepeat_msg.attr("class","error");
        return false;
      }
      if(!pwdRepeat_msg.hasClass("hide")){
        pwdRepeat_msg.text("");
        pwdRepeat_msg.attr("class","hide");
      }
      return true;
    }
    // 定义Email验证的函数
    function emailValidator(){
      var value = $("#mail").val();
      var email_msg = $("#mail_msg");
      if(value==""||value==null){
        email_msg.text("Email不能为空");
        email_msg.attr("class","error");
        return false;
      }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)){
        email_msg.text("Email格式不正确");
        email_msg.attr("class","error");
        return false;
      }
      if(!email_msg.hasClass("hide")){
        email_msg.text("");
        email_msg.attr("class","hide");
      }
      return true;
    }
    function validateForm(){
      if(!userValidator()||!pwdValidator()||!pwdRepeatValidator()||!emailValidator()){
        return false;
      }
      return true;
    }
  </script>
</body>
</html>

Second type:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }

      form {
        width: 570px;
        height: 300px;
        margin: 100px auto;
      }

      label {
        width: 64px;
        float: left;
        clear: left;
        height: 36px;
        line-height: 36px;
        margin-top: 10px;
      }

      input {
        width: 300px;
        height: 36px;
        line-height: 36px;
        margin-top: 10px;
        text-indent: 8px;
        font-size: 16px;
        font-family: "微软雅黑";
        border: 1px solid #ccc;
        float: left;
      }

      #sub {
        width: 302px;
        height: 40px;
        border: 1px solid #ccc;
        background: #888;
        color: #fff;
        font-size: 18px;
        text-indent: 0;
      }

      .spa {
        height: 36px;
        line-height: 36px;
        width: 204px;
        display: inline-block;
        float: left;
        font-size: 12px;
        color: #BD362F;
        text-indent: 10px;
        margin-top: 10px;
      }
    </style>
  </head>

  <body>
    <form action="" method="post">
      <label id="name">姓 名:</label><input type="text" name="username" id="username" value="" placeholder="请输入姓名" /><span class="spa spa1"></span><br />
      <label id="phone">手机号:</label><input type="text" name="userphone" id="userphone" value="" placeholder="请输入手机号" /><span class="spa spa2"></span><br />
      <label id="address">地 址:</label><input type="text" name="useraddress" id="useraddress" value="" placeholder="请输入地址" /><span class="spa spa3"></span><br />
      <label>    </label><input type="submit" value="注册" id="sub" />
    </form>
    <script src="http://code.jquery.com/jquery-1.4.1.js"></script>
    <script type="text/javascript">
      window.onload = function() {
          $("#username").focus()
        }
        /************************ 失焦判断 **********************************/
      $("input").blur(function() {
          $(".spa").css("color", "#BD362F")
          if($(this).is("#username")) { //姓名判断
            var na = /^[\u4E00-\u9FA5]{2,4}$/
            if($("#username").val() != "") {
              if(!(na.test($("#username").val()))) {
                $(".spa1").text("请输入2-4个汉字");
                $(this).css("border", "1px solid #BD362F")
                return false;
              } else if(na) {
                $(".spa1").text("");
                return true;
              }
            } else {
              $(".spa1").text("");
            }
          }
          if($(this).is("#userphone")) { //手机号判断
            var ph = /^1[3|5|7|8|][0-9]{9}$/
            if($("#userphone").val() != "") {
              if(!(ph.test($("#userphone").val()))) {
                $(".spa2").text("请输入正确手机号");
                $(this).css("border", "1px solid #BD362F")
                return false;
              } else if(ph) {
                $(".spa2").text("");
                return true;
              }
            } else {
              $(".spa2").text("");
            }
          }

          if($(this).is("#useraddress")) { //地址判断
            var ad = /^(?=.*?[\u4E00-\u9FA5])[\dA-Za-z\u4E00-\u9FA5]{8,32}/;
            if($("#useraddress").val() != "") {
              if(!(ad.test($("#useraddress").val()))) {
                $(".spa3").text("请输入正确地址");
                $(this).css("border", "1px solid #BD362F")
                return false;
              } else if(ad) {
                $(".spa3").text("");
                return true;
              }
            } else {
              $(".spa3").text("");
            }
          }
        })
        /********************** 聚焦提示 ************************/
      $("input").focus(function() {
          if($(this).is("#username")) {
            $(".spa1").text("四个汉字").css("color", "#aaa")
            $(this).css("border", "1px solid #aaa")
          }
          if($(this).is("#userphone")) {
            $(".spa2").text("11位手机号码").css("color", "#aaa")
            $(this).css("border", "1px solid #aaa")
          }
          if($(this).is("#useraddress")) {
            $(".spa3").text("最少8个字符(汉字、字母和数字)").css("color", "#aaa")
            $(this).css("border", "1px solid #aaa")
          }
        })
        /*********************** 提交验证 ***************************/
      $("#sub").click(function() {
        var na = /^[\u4E00-\u9FA5]{2,4}$/; //姓名正则
        var ph = /^1[3|5|7|8|][0-9]{9}$/; //手机号正则
        var ad = /^(?=.*?[\u4E00-\u9FA5])[\dA-Za-z\u4E00-\u9FA5]{8,32}/; //地址正则
        if(na.test($("#username").val()) && ph.test($("#userphone").val()) && ad.test($("#useraddress").val())) {
          return true;
        } else {
          if($("#username").val() == "") {
            $(".spa1").text(&#39;请你填写用户名&#39;)
          }
          if($("#userphone").val() == "") {
            $(".spa2").text(&#39;请你填写手机号&#39;)
          }
          if($("#useraddress").val() == "") {
            $(".spa3").text(&#39;请你填写地址&#39;)
          }
          return false;
        }
      })
    </script>
  </body>
</html>

The above is the entire content of this article, I hope it will be helpful to everyone The learning is helpful, and I hope everyone will support the PHP Chinese website.

For more related articles on the two implementation methods of JavaScript form validation, please pay attention to the PHP Chinese website!

Statement
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
JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.