Help with adding e-mail validation to web Form

Thanks for all the previous help.
I have this ‘existing’ code that now works successfully not allowing the Form to complete unless both Name and Email fields are populated. Now, I’d like to make sure the entered email address is valid before ‘success’.

And I tried this code snippet (unless you have a better idea), but not sure how to integrate it into the existing code. Anywhere I place it prevents the Form from displaying ‘error’ or ‘success’ messages:

function validEmail(string $email): bool {
	// check if e-mail address is well-formed
	if ( filter_var($email, FILTER_VALIDATE_EMAIL)) {
	  return true;
	return false;

Here’s the ‘existing’ code:

header('Content-type: application/json');

$errors         = array();      // array to hold validation errors
$response = ['success' => false];

    if (empty($_POST['name'])|| empty($_POST['email'])){
    $response['success'] = false;
    } else {
    $response['success'] = true;

   echo json_encode($response);

    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;

    if(empty($errors)) {
	$to = '';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from:';

	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";

	$message = "Hello {$_POST['name']}, ~ Thank you\r\n\r\n";

   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );

		$data = ['success' => true];

I appreciate any comments/guidance

To start with, you have an errors array and never use it. What is the point of json encoding a response that is only going to be true or false that only gets echo’d for no apparent reason?

Show us how you used it, where you put it, how you called it and what you did with the result returned from it.

At a glance, all it really does is encapsulate the filter_var() function call which returns a Boolean to indicate a valid email address, so there’s no big advantage to having it in a function.

You should also look at using an email library other than the built-in mail() function as I read on here that can be quite unreliable. People talk about PHPMailer being a good one to look at, but there may be better ones now.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.