Home Web Front-end JS Tutorial Summary of commonly used javascript form validation_javascript skills

Summary of commonly used javascript form validation_javascript skills

May 16, 2016 pm 03:32 PM
javascript form validation

Explanation with examples: Verify whether the input is a number and whether it meets the number of digits. If it is wrong, provide a friendly reminder.

Rendering:

<!DOCTYPE html>
<html>
<body>

<h1>我的第一段 JavaScript</h1>

<p>请输入数字。如果输入值不是数字,浏览器会弹出提示框。</p>

<input id="demo" type="text">

<script>
function myFunction()
{
var x=document.getElementById("demo").value;
if(x==""){
alert("输入不能为空");
return;
}

if(isNaN(x)){
alert("请输入数字");
return;
}

if(x.length!=6){
alert("请输入6位数字");
return;
}

}
</script>
<button type="button" onclick="myFunction()">点击这里</button>
</body>
</html>

Copy after login

The above example contains many commonly used form validation codes, which are shared with you below:

1. Verification form

2. Verify nickname

3. Calculate nickname length

4. Verify whether the nickname exists

5. Verify mobile phone number

6. Verify password

7. Verification email

8. Verify verification code

9. Determine whether to select

Registration verification as an example:

<script language="JavaScript" src="js/jquery-1.9.1.min.js" type="text/javascript"></script>

//验证表单
     function vailForm(){
       var form = jQuery("#editForm");
       if(!vailNickName())return;
       if(!vailPhone())return;
       if(!vailPwd())return;
       if(!vailConfirmPwd())return;
       if(!vailEmail())return;
       if(!vailCode())return;
       if(!vailAgree())return;
       form.submit();
     }

//验证昵称
     function vailNickName(){
       var nickName = jQuery("#nickName").val();
       var flag = false;
       var message = "";
       var patrn=/^\d+$/;
       var length = getNickNameLength();
       if(nickName == ''){
         message = "昵称不能为空!";
       }else if(length<4||length>16){
         message = "昵称为4-16个字符!";
       } else if(checkNickNameIsExist()){
         message = "该昵称已经存在,请重新输入!";
       }else{
         flag = true;
       }
       if(!flag){
         jQuery("#nickNameDiv").removeClass().addClass("ui-form-item has-error");
         jQuery("#nickNameP").html("");
         jQuery("#nickNameP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);
         //jQuery("#nickName").focus();
       }else{
         jQuery("#nickNameDiv").removeClass().addClass("ui-form-item has-success");
         jQuery("#nickNameP").html("");
         jQuery("#nickNameP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该昵称可用");
       }
       return flag;
     }

//计算昵称长度
     function getNickNameLength(){
       var nickName = jQuery("#nickName").val();
       var len = 0;
      for (var i = 0; i < nickName.length; i++) {
         var a = nickName.charAt(i);

      //函数格式:stringObj.match(rgExp) stringObj为字符串必选 rgExp为正则表达式必选项
      //返回值:如果能匹配则返回结果数组,如果不能匹配返回null
         if (a.match(/[^\x00-\xff]/ig) != null){
          len += 2;
        }else{
          len += 1;
        }
      }
       return len;
     }

//验证昵称是否存在
     function checkNickNameIsExist(){
       var nickName = jQuery("#nickName").val();
       var flag = false;
       jQuery.ajax(
        { url: "checkNickName&#63;t=" + (new Date()).getTime(),
          data:{nickName:nickName},
          dataType:"json",
             type:"GET",
             async:false,
             success:function(data) {
             var status = data.status;
             if(status == "1"){
               flag = true;
             }
           }
      });
      return flag;
     }

//验证手机号
     function vailPhone(){
       var phone = jQuery("#phone").val();
       var flag = false;
       var message = "";
       //var myreg = /^(((13[0-9]{1})|159|153)+\d{8})$/;
       var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-3]{1})|(18[5-9]{1}))+\d{8})$/;
       if(phone == ''){
         message = "手机号码不能为空!";
       }else if(phone.length !=11){
         message = "请输入有效的手机号码!";
       }else if(!myreg.test(phone)){
         message = "请输入有效的手机号码!";
       }else if(checkPhoneIsExist()){
         message = "该手机号码已经被绑定!";
       }else{
         flag = true;
       }
       if(!flag){
         jQuery("#phoneDiv").removeClass().addClass("ui-form-item has-error");
         jQuery("#phoneP").html("");
         jQuery("#phoneP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);
         //jQuery("#phone").focus();
       }else{
         jQuery("#phoneDiv").removeClass().addClass("ui-form-item has-success");
         jQuery("#phoneP").html("");
         jQuery("#phoneP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该手机号码可用");
       }
       return flag;
     }

//验证手机号是否存在
       function checkPhoneIsExist(){
         var phone = jQuery("#phone").val();
         var flag = true;
         jQuery.ajax(
          { url: "checkPhone&#63;t=" + (new Date()).getTime(),
            data:{phone:phone},
            dataType:"json",
               type:"GET",
               async:false,
               success:function(data) {
               var status = data.status;
               if(status == "0"){
                 flag = false;
               }
             }
        });
        return flag;
       }

 //验证密码
     function vailPwd(){
       var password = jQuery("#password").val();
       var flag = false;
       var message = "";
       var patrn=/^\d+$/;
       if(password ==''){
         message = "密码不能为空!";
       }else if(password.length<6 || password.length>16){
         message = "密码6-16位!";
       }else if(patrn.test(password)){
         message = "密码不能全是数字!";
       }else{
         flag = true;
       }
       if(!flag){
         jQuery("#passwordDiv").removeClass().addClass("ui-form-item has-error");
         jQuery("#passwordP").html("");
         jQuery("#passwordP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);
         //jQuery("#password").focus();
       }else{
         jQuery("#passwordDiv").removeClass().addClass("ui-form-item has-success");
         jQuery("#passwordP").html("");
         jQuery("#passwordP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该密码可用");
       }
       return flag;
     }

//验证确认密码
     function vailConfirmPwd(){
       var confirmPassword = jQuery("#confirm_password").val();
       var patrn=/^\d+$/;
       var password = jQuery("#password").val();
       var flag = false;
       var message = "";
       if(confirmPassword == ''){
         message = "请输入确认密码!";
       }else if(confirmPassword != password){
         message = "二次密码输入不一致,请重新输入!";
       }else if(patrn.test(password)){
         message = "密码不能全是数字!";
       }else {
         flag = true;
       }
       if(!flag){
         jQuery("#confirmPasswordDiv").removeClass().addClass("ui-form-item has-error");
         jQuery("#confirmPasswordP").html("");
         jQuery("#confirmPasswordP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);
         //jQuery("#confirm_password").focus();
       }else{
         jQuery("#confirmPasswordDiv").removeClass().addClass("ui-form-item has-success");
         jQuery("#confirmPasswordP").html("");
         jQuery("#confirmPasswordP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>密码正确");
       }
       return flag;
     }

//验证邮箱
     function vailEmail(){
       var email = jQuery("#email").val();
       var flag = false;
       var message = "";
       var myreg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; 
       if(email ==''){
         message = "邮箱不能为空!";
       }else if(!myreg.test(email)){
         message = "请输入有效的邮箱地址!";
       }else if(checkEmailIsExist()){
         message = "该邮箱地址已经被注册!";
       }else{
         flag = true;
       }
       if(!flag){
         jQuery("#emailDiv").removeClass().addClass("ui-form-item has-error");
         jQuery("#emailP").html("");
         jQuery("#emailP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);
         //jQuery("#email").focus();
       }else{
         jQuery("#emailDiv").removeClass().addClass("ui-form-item has-success");
         jQuery("#emailP").html("");
         jQuery("#emailP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该邮箱可用");
       }
       return flag;
     }

//验证邮箱是否存在
     function checkEmailIsExist(){
       var email = jQuery("#email").val();
       var flag = false;
       jQuery.ajax(
        { url: "checkEmail&#63;t=" + (new Date()).getTime(),
          data:{email:email},
          dataType:"json",
             type:"GET",
             async:false,
             success:function(data) {
             var status = data.status;
             if(status == "1"){
               flag = true;
             }
           }
      });
      return flag;
     }

//验证验证码

 function vailCode(){
       var randCode = jQuery("#randCode").val();
       var flag = false;
       var message = "";
       if(randCode == ''){
         message = "请输入验证码!";
       }else if(!checkCode()){
         message = "验证码不正确!";
       }else{
         flag = true;
       }
       if(!flag){
         jQuery("#randCodeDiv").removeClass().addClass("ui-form-item has-error");
         jQuery("#randCodeP").html("");
         jQuery("#randCodeP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);
         //jQuery("#randCode").focus();
       }else{
         jQuery("#randCodeDiv").removeClass().addClass("ui-form-item has-success");
         jQuery("#randCodeP").html("");
         jQuery("#randCodeP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>");
       }
       return flag;
     }

//检查随机验证码是否正确
     function checkCode(){
       var randCode = jQuery("#randCode").val();
       var flag = false;
       jQuery.ajax(
        { url: "checkRandCode&#63;t=" + (new Date()).getTime(),
          data:{randCode:randCode},
          dataType:"json",
             type:"GET",
             async:false,
             success:function(data) {
             var status = data.status;
             if(status == "1"){
               flag = true;
             }
           }
      });
      return flag;
     } 

//判断是否选中
 function vailAgree(){
       if(jQuery("#agree").is(":checked")){
         return true;
       }else{
         alert("请确认是否阅读并同意XX协议");
       }
       return false;
     }
function delHtmlTag(str){
  var str=str.replace(/<\/&#63;[^>]*>/gim,"");//去掉所有的html标记
  var result=str.replace(/(^\s+)|(\s+$)/g,"");//去掉前后空格
  return result.replace(/\s/g,"");//去除文章中间空格
}

Copy after login

The above is a practical JavaScript form verification, I hope you like it.

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles