duanliao6789 2017-01-12 20:57
浏览 98
已采纳

通过php和jQuery验证电子邮件

I want to validate email field which I take on input by using php and jquery. But I am unable to figure out my mistake in my program.

Below is the code in index.html

<!DOCTYPE html>
<html lang="en">
    <head>
         <title>
         </title>
         <meta charset="utf-8" />
         <link rel="stylesheet" type="text/css" href="css/custom.css" />
    </head>
    <body>
        <p>Email: <input type="text" id="myInput" /></p>
        <p id="feedbackDiv"></p>
        <p><input type="button" id="myButton" value="Check" /></p>

    <script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
    <script type="text/javascript" src="js/custom.js" ></script>
    </body>
</html>

Below is the code in custom.js

$(document).ready(function(){
    $('#myButton').on('click',function(){
        var x = $('#myInput').val();

        function validateEmail(mail){
            $.post('php/email.php',{email_value_server: mail},function(returnData){
                $('#feedbackDiv').html(returnData);
            });
        }

        $('#myInput').focusin(function(){
            if(x === ''){
                $('#feedbackDiv').html('Please fill the email address.');
            }else{
                validateEmail(x);
            }
        }).blur(function(){
            $('#feedbackDiv').html('');
        }).keyup(function(){
            validateEmail(x);
        });
    });
});

Below is the code in email.php

<?php
    $y = $_POST['email_value_server'];
    if(isset($y)){
         if(!empty($y)){
             if(filter_var($y,FILTER_VALIDATE_EMAIL) === false){
                 echo "This doesn't appear to be valid email address.";
             }else{
                 echo "Valid email address.";
             }
         }
    }
?>

I am a beginner in jQuery and php. Please comment below for any query.

  • 写回答

5条回答 默认 最新

  • dragon321723 2017-01-15 16:32
    关注

    After looking through your code, there was quite many things. Sometimes in programming it is important to define and write down what you want to achieve before jumping in programming it. Starting a head with programming can sometimes lead to problem like the one you have here.

    General feedback

    1. Without going in bugs detail, my first observation is that you are trying to check and validate email, while typing and on submitting, it fills like you have an idea and want to try many concepts at once and that would give conflicts. For instance, you are trying to click in jQuery but at the same time trying to use keyup methods, this will never work because keyup can not work if not click is on and the other way around.
    2. My second observation and this is something I really encourage any beginner programmer to learn, to giving the proper name conventions to property. Like id=”myInput” just call id=myEmailInput, id=emailInput or myButton just call it submitButton or submitBtn etc. The important thing is to call it something any one can understand, just imagine you have several buttons and input fields, it will be hard to remember which button and what is myInput, that is some thing also left to you and your taste.
    3. Even thus if your code was working it is not a good practice to check invalid e-mail over Ajax by typing (keyup) method, that will cost you a lot of lookup at server side. I would make my code checking email format at first step at client side and when it looks identical, than make a server/php look up so you could eventually make a database lookup or what ever action.

    There are few other things as well. Checking email can be easily done by html5 (HTML5 Email Validation) and you can improve it or make extra features by using JavaScript, jQuery or PHP or any other technology alone or both, all depending on your goal and the requirement.

    Back to your code, as answer I would allow myself to modify your code to make it working and added some explanation. That said this can be done many ways, and my answer is just example you change it the way it fits you best.

    I have also best possible try to keep it as your style and with PHP, jQuery and Ajax all that in hope that it can help you achieve your goal and improve your skills.

    HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>
        </title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/custom.css"/>
    </head>
    <body>
    <p>Email: <input type="text" id="myInput"/>
    <span id="feedbackDiv"></span>
    </p>
    <p><input type="button" id="myButton" value="Check"/></p>
    <script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
    <script type="text/javascript" src="js/custom.js"></script>
    </body>
    </html>
    

    In HTML the main change I just used SPAN to keep the error/success message in one line.

    PHP:

    <?php
    
    if (isset($_POST['email']))
    {
        $email = $_POST['email'];
    
        if (filter_var($email, FILTER_VALIDATE_EMAIL))
        {
            http_response_code(200);
            echo $email . ' is valid email';
            // Do eventually email look up in database
            // something like
            // if email exist in db than msg "Email Exist" else msg "Email Does not Exist"
        } else {
            http_response_code(412);
            // Do something else or just leave it as is
        }
    }
    

    To learn more about http status code. And here I have changed the code logic a bit, so php can return a http status to Ajax call.

    JavaScript:

    $(document).ready(function () {
    
        // if you need to disable and enable button depending on email validity.
        //disableBtn(true);
    
        // each time you press and release the key it will check
        $('#myInput').on('keyup', function (e) {
            var $input = $(this);
            console.log($input);
            action($input);
        });
    
        // you can always click Check for force check
        $('#myButton').on('click', function (e) {
            var $input = $('#myInput');
            action($input);
        });
    
        function action(passData) {
    
            var $input = passData
                , value = $input.val()
                , data = {
                email: value
            };
    
            // if empty alert message would disappear
            if (value != "") {
                // Pre validate email on client side to reduce the server lookup
                if (validateEmailOnClientSide(value)) {
                    $.ajax({
                        method: 'POST',
                        url: 'email.php',
                        data: data,
                        // if server return valid email then we get Green text
                        success: function (returnData) {
                            $('#feedbackDiv').css('color', 'green').html(returnData);
                            //disableBtn(true);
                        },
                        // if server return invalid email then we get Red text
                        error: function (xhr, status, error) {
                            $('#feedbackDiv').css('color', 'red').html(value + " is not valid email");
                            //disableBtn(false);
                        },
                        dataType: 'text'
                    });
                } else {
                    // Red text from browser side
                    $('#feedbackDiv').css('color', 'red').html(value + " is not valid email");
                    //disableBtn(false);
                }
            } else {
                // Emptying text
                $('#feedbackDiv').html("");
                //disableBtn(false);
            }
    
        }
    
        function validateEmailOnClientSide(email) {
            var re = /\S+@\S+\.\S+/;
            return re.test(email);
        }
    
        function disableBtn(boolean) {
            $("#myButton").attr("disabled", boolean);
        }
    
    });
    

    You could eventually disable submit button if the email is invalid and enable it if it become valid, just un-comment all functions in code disableBtn(true); and disableBtn(false);

    Output example: And here is an example, where you get Green or Red message on fly by typing a valid and invalid email. Of course if you submit Check an invalid email you have the same process as typing it.

    Email validation output example

    Some of the references I used:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?