博客列表 >用PHP+AJAX将表单中文本域验证 -- 2018年4月18日16点44分

用PHP+AJAX将表单中文本域验证 -- 2018年4月18日16点44分

hongda的博客
hongda的博客原创
2018年04月18日 16:44:55738浏览

以下用jQuery, ajax 和 php完成服务器端对用户输入的验证:

前端代码如下

实例

<!DOCTYPE html>
<html>
<head>
    <meta  charset="UTF-8">
    <title>php 处理表单</title>
    <style type="text/css">
        table{
            background-color: wheat;
            box-shadow: 3px 3px 3px #888;
            border-radius: 15px;
            padding: 15px;
            margin: 30px auto;
        }
        table td{
            padding: 8px;
        }
        table caption{
            font-size: 1.5em;
            margin-bottom: 10px;
        }
        textarea{
            resize: none;
        }
        form button{
            width: 100px;
            height: 30px;
            border: none;
            background-color: skyblue;
            color: white;
        }
        form button:hover{
            background-color: orangered;
            font-size: 1.1em;
            cursor: pointer;
        }

    </style>
</head>
<body>
<form>
    <table>
        <caption>register</caption>
        <tr>
            <td><label for="email">email:</label></td>
            <td><input type="text" name="email" id="email" autofocus=""></td>
        </tr>
        <tr>
            <td><label for="password1">password:</label></td>
            <td><input type="password" name="password1" id="password1"></td>
        </tr>
        <tr>
            <td><label for="password2">comfirm your password:</label></td>
            <td><input type="password" name="password2" id="password2"></td>
        </tr>
        <tr>
            <td><label for="sex">Gender:</label></td>
            <td>
                <input type="radio" name="gender" id="male" value="male"><label for="male">Male</label>
                <input type="radio" name="gender" id="female" value="female"><label for="female">Female</label>
                <input type="radio" name="gender" id="secret" value="secret" checked><label for="secret">secret</label>
            </td>
        </tr>
        <tr>
            <td><label for="level">level:</label></td>
            <td>
                <select name="level" id="level">
                    <option value="0">Junior</option>
                    <option value="1" selected>Middle</option>
                    <option value="2">Senior</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><label for="php">language:</label></td>
            <td>
                <input type="checkbox" name="language" id="php" checked><label for="php">php</label>
                <input type="checkbox" name="language" id="java" ><label for="java">java</label>
                <input type="checkbox" name="language" id="python" ><label for="python">python</label>
                <input type="checkbox" name="language" id="C" ><label for="C">C</label>
            </td>
        </tr>
        <tr>
            <td><label for="comment"></label</td>
            <td>
                <textarea name="comment" id="comment" rows="3" cols="20"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <button type="submit" name="submit" id="submit" value="submit">Submit</button>
            </td>
        </tr>
    </table>
</form>


<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
    //using ajax to compelete the form valiadation, using post method
    //1.email validation
    $('#email').blur(function () {
        //using post method
        //在URL里面加上参数   让服务器端的php能够判断验证的是什么
        $.post('check.php?check=email','email='+  $('#email').val(),function (data) {
            switch (data.status) {
                case 0:
                    $('td').find('span').remove()
                    $('#email').after('<span>').next().text(data.msg).css('color','red').prev().focus()
                    break;
                case 1:
                    $('td').find('span').remove()
                    $('#email').after('<span>').next().text(data.msg).css('color','red').prev().focus()
                    break;
                case 2:
                    $('td').find('span').remove()
                    $('#email').after('<span>').next().text(data.msg).css('color','green')
                    break;
            }
        },'json')
    })

    //2.密码验证
    $('#password1').blur(function () {
        if ( $('#email').val().length == 0){
            return false;
        }
        $.post('check.php?check=password1', 'password1=' + $('#password1').val(), function (data) {
            if (data.status == 0){
                $('td').find('span').remove()
                $('#password1').after('<span>').next().text(data.msg).css('color','red').prev().focus()
            } else {
                $('td').find('span').remove()
            }

        }, 'json')
    })

    //3.确认密码
    $('#password2').blur(function () {
        if ( $('#email').val().length == 0 ||  $('#password1').val().length == 0){
            return false;
        }
        //把数据写成json把数据传到php
        $.post('check.php?check=password2', {
            password1: $('#password1').val(),
            password2: $('#password2').val()
    }, function (data) {
            switch (data.status){
                case 0:
                    $('td').find('span').remove()
                    $('#password2').after('<span>').next().text(data.msg).css('color','red').prev().focus()
                    break;
                case 1:
                    $('td').find('span').remove()
                    $('#password2').after('<span>').next().text(data.msg).css('color','red').prev().focus()
                    break;
                case 2:
                    $('td').find('span').remove()
                    $('#password2').after('<span>').next().text(data.msg).css('color','green')
                    break;
            }
        }, 'json')
    })

    //4.确认文字域
    $('#comment').blur(function () {
        if ( $('#email').val().length == 0 ||  $('#password1').val().length == 0  ||  $('#password2').val().length == 0  ) {
            return false;
        }
        $.post('check.php?check=comment', 'comment=' + $('#comment').val(), function (data) {
            if (data.status == 0){
                $('td').find('span').remove()
                $('#comment').after('<span>').next().text(data.msg).css('color','red').prev().focus()
            } else if (data.status == 1) {
                $('td').find('span').remove()
                $('#comment').after('<span>').next().text(data.msg).css('color','red').prev().focus()
            } else  if (data.status == 2) {
                $('td').find('span').remove()
                $('#comment').after('<span>').next().text(data.msg).css('color','green')
            }
        }, 'json')
    })


</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

php服务器端代码如下:

实例

<?php
/**
 * Created by PhpStorm.
 * User: hongda
 * Date: 17/04/2018
 * Time: 10:58 PM
 */


//echo '<pre>';
//print_r($email);
//echo $_GET['check'];
//using the value of check from url to decide which input should be validated


switch ($_GET['check']){
    //validate email
    case 'email':
        //get the value of email
       $email=$_POST['email'];
       //determine if the value of email is empty
       if (empty($email)){
           //using json_encode() to return jason
           exit(json_encode(['status'=>0,'msg'=>'email should not be empty!']));
       }
       //determine if the value of email is admin
       else if (in_array($email,['admin@php.cn','hongda@php.cn'])){
           exit(json_encode(['status'=>1,'msg'=>'This email cannot be used!']));
       }
       //return right message if users` input is legal
       else {
           exit(json_encode(['status'=>2,'msg'=>'you can use this email!']));
       }
        break;

       //validate password1
    case 'password1':
        //get the value of password1
        $password1=$_POST['password1'];

        //determine if the value of password1 is empty
        if (empty($password1)){
            //using json_encode() to return jason
            exit(json_encode(['status'=>0,'msg'=>'password should not be empty!']));
        }
        //return right message if users` input is legal
        else {
            exit(json_encode(['status'=>1,'msg'=>'you can use this password!']));
        }
        break;

      //validate confirm password
    case 'password2':
        //get the value of password1 and password2
        $password1=$_POST['password1'];
        $password2=$_POST['password2'];
        //determine if the value of password2 is empty
        if (empty($password2)){
            //using json_encode() to return jason
            exit(json_encode(['status'=>0,'msg'=>'confirm password should not be empty!']));
        }
        //determine if the value of password1 is not equal to password2
        else if ($password1 != $password2) {
            exit(json_encode(['status'=>1,'msg'=>'confirm password doesnot match first password']));
        }
        //return right message if users` input is legal
        else {
            exit(json_encode(['status'=>2,'msg'=>'password valiadation has passed']));
        }
        break;

        //validate comment
    case 'comment':
        //get the value of password1 and comment
        $comment=$_POST['comment'];
        //determine if the value of comment is empty
        if (empty($comment)){
            //using json_encode() to return jason
            exit(json_encode(['status'=>0,'msg'=>'text area should not be empty!']));
        }
        //determine if the length of comment is less or equal to 10
        else if (strlen($comment) <= 10 ) {
            exit(json_encode(['status'=>1,'msg'=>'text area too short input!']));
        }
        //return right message if users` input is legal
        else {
            exit(json_encode(['status'=>2,'msg'=>'text area valiadation has passed']));
        }
        break;

    default:
        break;


}

?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


总结:

以上通过jQuery ajax 把用户输入的值传给 php进行验证,其中有很多小技巧:

比如在ajax异步传值给php的时候,用链接后面参数传给服务器端,这次的 blur事件触发的验证是验证用户输入的哪部分;

比如用switch语句来根据服务器端返回的json里的status来输出验证反馈给用户。





声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议