键入php时验证文本框

时间:2015-11-28 20:42:21

标签: php html validation

我有一个带有文本输入字段的表单。当用户输入数据时,需要同时验证文本输入。

<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>

输入email文本框应在服务器端验证,但我不知道在输入时验证文本字段。

有没有办法用PHP脚本来做?

2 个答案:

答案 0 :(得分:2)

如果你愿意使用jQuery和PHP,这里有你能做的例子:

<强> 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 (&gt; = 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 :(得分:0)

这是通过PHP和Javascript实现的。在您键入时,Javascript通过对php的Ajax调用发送写入的数据,并返回...

正确的方法是验证代码

  1. 在javascript中,因为它正在打字。这是通过fun <S> TableColumn<S, LocalDateTime>.formatAsDateTime() = cellFormat { text = dateTimeFormatter.format(it) }
  2. 中的事件onkeydown="validate_email(this)"完成的
  3. 在提交表单之前,请确保电子邮件地址有效,方法是添加input。如果javascript函数email_valid返回true,则表单将被提交,否则不会提交。
  4. 在PHP中,因为正在发送完整的数据,请在onsubmit="return email_valid();"
  5. 中确认它确实是一个正确的电子邮件地址
相关问题