2

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.

Web_Designer
  • 72,308
  • 93
  • 206
  • 262
R K
  • 307
  • 7
  • 22
  • 2
    What is the error here? What do you expect to see and what do you really see? – u_mulder Jan 12 '17 at 21:01
  • If you don't get info in your `feedbackDiv` maybe you fail with sending data to the real file you need to. try simple `alert` in your function and if you don't get anything, maybe you sent data to the wrong file. You didn't say what is the error, so I can't help you – Danielius Jan 12 '17 at 21:04
  • @u_mulder: In console I don't say any error, it's blank.I expect to see message written in php file whether email address is valid or invalid. – R K Jan 12 '17 at 21:06

5 Answers5

6

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:

Community
  • 1
  • 1
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
  • I would definitely advocate for using HTML5. No JavaScript needed! – Luke Jan 16 '17 at 21:10
  • @Luke thx for your comment, I already mentioned that in my answer but my answer cover also OP main question, now OP has the choice to further work on what fits him best. – Maytham Fahmi Jan 17 '17 at 00:25
3

Change your index.html and your custom.js as in the below snippet.

$(document).ready(function(){
        function postEmail(emailObj){
              // Set to true, if an element (with a required attribute) has no value.
              if (emailObj.validity.valueMissing === true) {
                 alert("Empty email address!");
               } 
              // Set to true, if an element's value does not match its pattern attribute.
              if(emailObj.validity.patternMismatch === true) {
                 alert("Wrong pattern in email address!");
               }
              // Set to true, if an element's value exceeds its maxLength attribute.
              if(emailObj.validity.tooLong === true) {
                 alert("Too long email address!");
               }
              // Set to true, if an element's value is valid.
              if(emailObj.validity.valid === true) {
                console.log(emailObj.value);
                $.post('php/email.php',{email_value_server: emailObj.value},function(returnData){
                $('#feedbackDiv').html(returnData);
                });
               } 
            
        }   
        $('#myInput').on("keydown",function(e){
            // detect key that was pressed by it's code
            var keyCode = e.keyCode ? e.keyCode : e.which;
            // if enter was pressed post email
            if(keyCode===13) {
               var $_this = $(this).get(0);
                postEmail($_this);
            }   
        });
        // post email on button click
        $('#myButton').on("click",function(){
               var $_this = $('#myInput').get(0);
               postEmail($_this); 
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!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="email" id="myInput" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" maxLength="100" required></p> <!-- this way you validate input client-side also -->
            <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>
2

Your $('#myInput') bindings are embedded within your button's click handler. To start with, you need to move that code outside of the handler. Try this:

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

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

Update

If you only wish to send the email check on submit, (probably a good idea), then it is a little simpler.

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

    $('#myButton').click(function(){
        var x = $('#myInput').val();
        if(x){
            validateEmail(x);
        } else {
            $('#feedbackDiv').html('Please fill the email address.');
        }
    });
});

Your PHP needs some work too. The $y = $_POST['email_value_server'] will fail if it is not set. You need to check it like this:

<?php
    $y = isset($_POST['email_value_server']) ? $_POST['email_value_server'] : NULL;
    // this will also check for empty or NULL
    if(filter_var($y, FILTER_VALIDATE_EMAIL) === false){
         echo "This doesn't appear to be valid email address.";
    } else {
        echo "Valid email address.";
    }
?>
Michael Sacket
  • 897
  • 8
  • 13
0

There is a very simple way to correct this issue. Change the input type from text to email in your html:

<p>Email: <input type="email" id="myInput"/>  /*note the amendment*/
<span id="feedbackDiv"></span>
</p>

Then, when a user enters in the input box, they will be prompted for an @ sign to indicate an email address, and if no @ sign is entered, an error will be given.

You should also change your button to a submit, and enclose your input fields in a form.

What you would end up would be something like this:

<form action="email.php" method="POST">
<p>Email: <input type="email" id="myInput"/> 
<span id="feedbackDiv"></span>
</p>
<p><input type="submit" id="myButton" value="Check" /></p>
</form>

I hope this helps

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
0

//better to grab a value through id as class might be common for other entered field box in a form

$(document).ready(function() {               
$('#Email_id').focusout(function(){  

$('#Email_id').filter(function(){

               var emil=$('#Email_id').val();
          var emailReg = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
        if( !emailReg.test( emil ) ) {
            console.log('Please enter valid email');
            } else {
            console.log('Thank you for your valid email');
            }
            });
        });

});

Rahul Naik
  • 11
  • 3