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

一,利用键盘响应,在不刷新本页面的情况下验证表单输入是否合法
用户通过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
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
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

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

Video Face Swap

Video Face Swap

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

Hot Tools

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function