douluoyou9876 2015-11-28 20:42
浏览 16
已采纳

键入php时验证文本框[关闭]

I am having a form with a text input field. The text input need to be validated simultaneously when the user enters the data.

<form method="post" action="Newsletter/tester.php">
    <label for="email">email</label>
    <input type="text" name="email" placeholder="Enter your email  *" maxlength="50" required>
    <input type="submit" value="test">
</form>

The input email textbox should be validated on the server side, but I don't have any idea about validating the text field while typing.

Is there any way to do it using php script?

  • 写回答

2条回答 默认 最新

  • doudi1750 2015-11-28 21:02
    关注

    If you are willing to use jQuery and PHP, here's an exemple of what you can do:

    HTML

    <form action="Newsletter/tester.php" method="post">
        <input type="email" name="email" id="email-input">
        <button type="submit">Send</button>
        <br/>
        <span id="email-validate">Waiting for user input...</span>
    </form>
    

    jQuery

    jQuery(function($) {
    
        // When the user types something in the input
        $('#email-input').on('keyup', function(e) {
    
            // set the variables
            var $input = $(this)
            ,   value  = $input.val()
            ,   data   = {
                    email: value   
            };
    
            // perform an ajax call
            $.ajax({
                url: 'my/validator.php', // this is the target
                method: 'get', // method
                data: data, // pass the input value to server
                success: function(r) { // if the http response code is 200
                    $('#email-validate').css('color', 'green').html(r);
                    $('button').removeAttr('disabled');
                },
                error: function(r) { // if the http response code is other than 200
                    $('#email-validate').css('color', 'red').html(r);
                    $('button').attr('disabled', 'disabled');
                }
    
            });
        });
    
    });
    

    PHP (>= 5.4)

    <?php
    if(isset($_GET['email'])) {
        $email = $_GET['email'];
    
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(200);
            echo 'The email '.$email.' is valid';
        } else {
            http_response_code(412);
            echo 'The email '.$email.' is not valid';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊