DEV Community

Cover image for How To Validate Email Address In PHP with jQuery & Ajax?
Code And Deploy
Code And Deploy

Posted on • Edited on

How To Validate Email Address In PHP with jQuery & Ajax?

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/how-to-validate-email-address-in-php-with-jquery-ajax

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Are you thinking about how to validate the email address before saving it to your database? Don't worry it's easy in this example we will use adding Employees with their email addresses. But we need to prompt the user if their email address submitted is invalid.

how-to-validate-email-address-in-php-with-jquery-ajax

So first we will create functions.php and we will code here all functions that can be re-usable to your app. So we will add here the email validator function so I call it as isEmail function then I use preg_match to validate your email address string.

<?php

    function isEmail($email) 
    {
        return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email)) ? FALSE : TRUE;
    }

?>
Enter fullscreen mode Exit fullscreen mode

Then next our save.php function which uses for saving employee records. Here is the example I already include the functions.php in this file. Kindly check below the basic code in this file.

<?php require_once 'functions.php';?>

<?php

    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $email = $request['email']; //get email address value

    // Check if no errors
    if(isEmail($email)):
        // Do something here
    else://display errors
        // Do something here
    endif;

?>
Enter fullscreen mode Exit fullscreen mode

Okay as you can see we have require_once to include the functions.php file. Then we call the isEmail function we created above. Then check the email using if statement if the submitted email is valid.

So now I will show you the complete source code of the save.php file.

<?php require_once 'functions.php';?>

<?php
    $request = $_REQUEST; //a PHP Super Global variable which used to collect data after submitting it from the form
    $email = $request['email']; //get email address value
    $first_name = $request['first_name']; //get first name value
    $last_name = $request['last_name']; //get last name value
    $address = $request['address']; //get address value

    $servername = "localhost"; //set the servername
    $username = "root"; //set the server username
    $password = ""; // set the server password (you must put password here if your using live server)
    $dbname = "demos"; // set the table name

    // Defined $result as array
    $result = [];


    // Check if no errors
    if(isEmail($email)):
        $mysqli = new mysqli($servername, $username, $password, $dbname);

        if ($mysqli->connect_errno) {
          $result['response'] = "Failed to connect to MySQL: " . $mysqli->connect_error;
          exit();
        }

        // Set the INSERT SQL data
        $sql = "INSERT INTO employees (email, first_name, last_name, address)
        VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$address."')";

        // Process the query so that we will save the date of birth
        if ($mysqli->query($sql)) {
          $result['response'] = "Employee has been created.";
        } else {
          $result['response'] = "Error: " . $sql . "<br>" . $mysqli->error;
        }

        // Close the connection after using it
        $mysqli->close();

    else://display errors
        $result['has_error'] = 1;
        $result['response'] = "Email address is invalid.";
    endif;


    echo json_encode($result);


?>
Enter fullscreen mode Exit fullscreen mode

As you can see above code I store the result to an array called $result. Then under the display errors comment, I add has_error key =1 so that I will use it for my javascript and check if the submitted email is not valid.

Then I use json_encode to encode the result array so that easier to parse the data with JSON on the client-side or in the javascript end.

Then next about my javascript function called save() inside scripts.js file. Kindly check the below code.

function save() 
{
    $("#btnSubmit").on("click", function() {
        var $this           = $(this); //submit button selector using ID
        var $caption        = $this.html();// We store the html content of the submit button
        var form            = "#form"; //defined the #form ID
        var formData        = $(form).serializeArray(); //serialize the form into array
        var route           = $(form).attr('action'); //get the route using attribute action

        // Ajax config
        $.ajax({
            type: "POST", //we are using POST method to submit the data to the server side
            url: route, // get the route value
            data: formData, // our serialized array data for server side
            beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
                $this.attr('disabled', true).html("Processing...");
            },
            success: function (response) {//once the request successfully process to the server side it will return result here

                response = JSON.parse(response);

                // Check if there is has_error property on json response from the server
                if(!response.hasOwnProperty('has_error')) {
                    // Reload lists of employees
                    all();

                    // We will display the result using alert
                    Swal.fire({
                      icon: 'success',
                      title: 'Success.',
                      text: response.response
                    });

                    // Reset form
                    resetForm(form);
                } else {
                    // We will display the result using alert
                    Swal.fire({
                      icon: 'warning',
                      title: 'Error.',
                      text: response.response
                    });
                }

                $this.attr('disabled', false).html($caption);

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // You can put something here if there is an error from submitted request
            }
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

As you can see in the success function in ajax we have a response that comes from the Server-Side result. I parse the JSON then I check if the JSON has no has_error property then execute the success alert and reload the lists of employees function.

Then if JSON response has has_error property then the error will prompt. That's it I hope I can help you and integrate it into your project. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/how-to-validate-email-address-in-php-with-jquery-ajax if you want to download this code.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Thank you and happy coding!

Top comments (0)