Home Backend Development PHP Tutorial 基于PHP+Ajax实现表单验证的详解_php技巧

基于PHP+Ajax实现表单验证的详解_php技巧

May 17, 2016 am 08:58 AM
ajax php form validation

一,利用键盘响应,在不刷新本页面的情况下验证表单输入是否合法
用户通过onkeydown和onkeyup事件来触发响应事件。使用方法和onclick事件类似。onkeydown表示当键盘上的键被按下时触发,onkeyup和它正好相反,当键盘上的键被按下又抬起时触发。
两种常用调用方法:
(1)将事件添加到页面元素中,当用户输入完信息后,单击任意键,onkeydown事件被触发,并调用refer()函数。
这种方法最简单,最直接,格式如下:
复制代码 代码如下:


 

(2)通过window.onload加载,当页面被载入时,事件被载入。当用户输入信息时,每输入一个字母,都将触发该事件,在该事件调用的函数中,对用户输入信息进行判断。
复制代码 代码如下:

window.onload = function(){
 $('regname').onkeydown = function (){
  name = $('regname').value;
 }
}

使用onkeydown事件还可以实现对特定键的控制,包括键(event.keyCode==13)、空格键(event.keyCode==32)、键、键等所有的按键,这是通过在onkeydown事件中使用keyCode属性来实现的。KeyCode属性能够知道用户按下的是哪个键。

二,注册信息验证
通用函数,返回被触发的id元素对象
复制代码 代码如下:

function $(id){
 return document.getElementById(id);
}
window.onload事件,表示当前窗口被载入时触发。function(){...}表示当前页面被载入时所要进行的操作。
window.onload = function(){
 ...
}

function()函数解析;
首先将焦点定位到用户名文本框,方便用户操作。接下来声明了5个变量,这5个变量代表了5个要检测的数据的结果。当检测数据为合格时,将变量值设为"yes".
复制代码 代码如下:

$('regname').focus();
var cname1,cname2,cpwd1,cpwd2;  //声明了5个变量,表示要检测的5项数据chkreg()函数是每一次触发键盘事件后都要调用的,该函数判断5个变量的值,只有当所有变量都为"yes"时,注册按钮才会被激活。
function chkreg(){
 if((cname1 == 'yes') && (cname2 == 'yes') && (cpwd1 == 'yes') && (cpwd2 == 'yes')){
  $('regbtn').disabled = false;
 }else{
  $('regbtn').disabled = true;
 }
}

下面验证用户名,当用户输入注册名称时,该函数会把用户的每次输入都做一下正则判断,并根据结果设置不同的cname1的值。
复制代码 代码如下:

$('regname').onkeyup = function (){
 name = $('regname').value;  //获取注册名称
 cname2 = '';
 if(name.match(/^[a-zA-Z_]*/) == ''){
  $('namediv').innerHTML = '必须以字母或下划线开头';
  cname1 = '';
 }else if(name.length   $('namediv').innerHTML = '注册名称必须大于3位';
  cname1 = '';
 }else{
  $('namediv').innerHTML = '注册名称符合标准';
  cname1 = 'yes';
 }
 chkreg(); //调用chkreg()函数,判断5个变量是否正确
}

当用户名文本框失去焦点时,即用户输入完毕转到页面中其他元素的时候,将检测用户名是否重复。用户名判断使用Ajax技术调用了chkname.php(该页面用户名验证代码稍后贴出)并根据chkname.php的返回值在div标签中显示判断结果。
复制代码 代码如下:

$('regname').onblur = function(){
 name = $('regname').value;  //获取注册名称
 if(cname1 == 'yes'){ //当用户名称的格式输入合格后才进行这一步
  xmlhttp.open('get','chkname.php?name='+name,true);  //open()创建XMLHttpRequest初始化连接,Ajax创建新的请求
  xmlhttp.onreadystatechange = function(){  //当指定XMLHttpRequest为异步传输时(false),发生任何状态的变化,该对象都会调用onreadystatechange所指定的函数
   if(xmlhttp.readyState == 4){  //XMLHttpRequest处理状态,4表示处理完毕
    if(xmlhttp.status == 200){ //服务器响应的HTTP代码,200表示正常
     var msg = xmlhttp.responseText;  //获取响应页的内容
     if(msg == '1'){  //chkname.php页面查找数据库,数据库没有该用户返回1
      $('namediv').innerHTML="恭喜您,该用户名可以使用!";
      cname2 = 'yes';
     }else if(msg == '2'){ //数据库存在该用户返回0
      $('namediv').innerHTML="用户名被占用!";
      cname2 = '';
     }else{
      $('namediv').innerHTML=""+msg+"";
      cname2 = '';
     }
    }
   }
  }
  xmlhttp.send(null);
  chkreg(); //检测是否激活注册按钮
 }
}

验证密码,验证密码时,除了可以限制密码的长度外,还可以判断密码的强度。
复制代码 代码如下:

$('regpwd1').onkeyup = function(){
 pwd = $('regpwd1').value;
 pwd2 = $('regpwd2').value;
 if(pwd.length   $('pwddiv1').innerHTML = '密码长度最少需要6位';
  cpwd1 = '';
 }else if(pwd.length >= 6 && pwd.length   $('pwddiv1').innerHTML = '密码符合要求。密码强度:弱';
  cpwd1 = 'yes';
 }else if((pwd.match(/^[0-9]*$/)!=null) || (pwd.match(/^[a-zA-Z]*$/) != null )){
  $('pwddiv1').innerHTML = '密码符合要求。密码强度:中';
  cpwd1 = 'yes';
 }else{
  $('pwddiv1').innerHTML = '密码符合要求。密码强度:高';
  cpwd1 = 'yes';
 }
 if(pwd2 != '' && pwd != pwd2){
  $('pwddiv2').innerHTML = '两次密码不一致!';
  cpwd2 = '';
 }else if(pwd2 != '' && pwd == pwd2){
  $('pwddiv2').innerHTML = '密码输入正确';
  cpwd2 = 'yes';
 }
 chkreg();
}

二次密码判断比较简单,只要判断第二次输入密码是否和第一次输入相等。
复制代码 代码如下:

$('regpwd2').onkeyup = function(){
 pwd1 = $('regpwd1').value;
 pwd2 = $('regpwd2').value;
 if(pwd1 != pwd2){
  $('pwddiv2').innerHTML = '两次密码不一致!';
  cpwd2 = '';
 }else{
  $('pwddiv2').innerHTML = '密码输入正确';
  cpwd2 = 'yes';
 }
 chkreg();
}

上面是必须填写信息,如果用户希望填写更详细的资料,可单击"详细资料按钮"
复制代码 代码如下:

$('morebtn').onclick = function(){
 if($('morediv').style.display == ''){
  $('morediv').style.display = 'none';
 }else{
  $('morediv').style.display = '';
 }
}

E-mail格式验证,输入字符串中必须包含@和.,同时这两个字符串的位置既不能在首尾也不能连在一起
复制代码 代码如下:

$('email').onkeyup = function(){
 emailreg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
 $('email').value.match(emailreg);
 if($('email').value.match(emailreg) == null){
  $('emaildiv').innerHTML = '错误的email格式';
  cemail = '';
 }else{
  $('emaildiv').innerHTML = '输入正确';
  cemail = 'yes';

 }
 chkreg();
}

三,检测用户名(chkname.php)
复制代码 代码如下:

session_start();
include_once "conn/conn.php";
$reback = '0';
$sql = "select * from tb_member where name='".$_GET['name']."'";
$num = $conne->getRowsNum($sql);
if($num == 1){
 $reback = '2';
}else if($num == 0){
 $reback = '1';
}else{
 $reback = $conne->msg_error();
}
echo $reback;
?>

四,XMLHttpRequest函数初始化
复制代码 代码如下:

// JavaScript Document
var xmlhttp = false;
if (window.XMLHttpRequest) {          //Mozilla、Safari等浏览器
 xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {         //IE浏览器
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {}
 }
}
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles