Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error message displays even when the submit button hasn't been clicked and the page refreshes if the email format is incorrect.

Below is the snippet of my code:

<?php

$emailErr = "";
$email = "";

if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
  
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
    else{
        header("Location:create.php");
    }
  }

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
    
?>

function ShowHideDiv() {
  var chkYes1 = document.getElementById("chkYes1");
  var dvtext1 = document.getElementById("dvtext1");
  var chkYes2 = document.getElementById("chkYes2");
  var dvtext2 = document.getElementById("dvtext2");
  var button = document.getElementById("button");
  dvtext1.style.display = chkYes1.checked || chkYes2.checked ? "block" : "none";
  dvtext2.style.display = chkYes2.checked ? "block" : "none";
  btn1.style.display = chkYes1.checked ? "block" : "none";
  btn2.style.display = chkYes2.checked ? "block" : "none";
}
<div class="content login-container">
  <div class="form-login">
     <label for="chkYes1">
        <input type="radio" id="chkYes1" name="chk" onclick="ShowHideDiv()" />
        I am new on Swadonline
      </label>
      <br>
      <br>
      <div id="dvtext1" style="display: none" class="lgntxt">
        Please enter your Email Address *
        <br>
        <input type="text" id="txtBox" name="email" />
      </div>
      <button style="display: none" id="btn1" class="btn third" type="submit" name="submit" value="Submit">CONTINUE</button>
  </div>
</div>
  

Answer №1

Modify this line in HTML

<button style="display: none" id="btn1" class="btn third" type="submit" name="submit" value="Submit">CONTINUE</button>

to

<input type="submit"  style="display: none" id="btn1" class="btn third"  name="my_form_submit" value="CONTINUE">

Now, update the following in your PHP code:

<?php

// initialize variables as empty strings
$emailErr = "";
$email = "";
if(isset($_POST['my_form_submit'])){ // only validate if form is submitted

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
      } else {
        $email = test_input($_POST["email"]);
        // check email format
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $emailErr = "Invalid email format"; 
        }
        else{
            header("Location:create.php");
        }
      }

    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }
}

?>

Answer №2

After using this method for submitting forms in the past, I discovered the effectiveness of incorporating PHPMailer into any project.

  • PHPMailer makes setting up email functionality a breeze and has consistently delivered reliable results.
  • For form validation, simply adding the 'required' attribute to fields is usually sufficient as modern browsers handle the rest automatically.

Hopefully, this information proves useful to you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

clearing all input fields upon submission in React Native

I need help resolving an error that occurs when I try to clear text input fields on a button press. Instead of clearing the fields, it throws an undefined error because I am trying to set the value as {this.state.inputTextValue} and then clear it using set ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

Incorporating a header include on every page throughout my website

Is there a way to include headers and footers in your HTML web pages without having to duplicate code on every page? I understand that this can be done using PHP, but what if you are creating a website solely with HTML? If there is no solution to avoid r ...

Tips for understanding nested JSON or array data structure?

My data is stored in a constant called translations and it looks like this: { "item-0": { "_quote-translation": "translation Data", "_quote-translation-language": "English", "_quote-trans ...

How many elements were dynamically added to the <div>?

I am using jQuery to dynamically insert images into a div element. After successfully adding an image, I have included an alert(). Is there a way in jQuery to verify if a series of elements has been added to a div tag? ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Preventing default behavior in a JQuery post request

Encountering an issue with jQuery functionality on a mobile device. function send() { $.post("scripts/post.php", { username: $("input[name=username]").val(), password: $("input[name=password]").val() }, function(data) { if ($(".data div" ...

The items are misaligned in a horizontal position

The 4 divs are styled with a width of 23% and displayed using inline-block. They have a fixed height of 220px and no margin applied. However, the issue arises as they are not aligning horizontally Despite attempting to adjust the height and width paramete ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

Restrict the amount of displayed information in Vue

I'm having trouble creating a Vue button that limits the display of items fetched from an API. The goal is to only show 3 out of 10 questions initially, and when the "showmore" button is clicked, another set of 3 should be displayed, and so on. Howeve ...

How can I assign several Objects to a single array?

My goal is to save several objects into an array. Specifically, I have five objects named obj1, obj2, obj3, obj4, and obj5. ...

The PhoneGap Android whitelist feature seems to be malfunctioning and preventing navigation to the next page

Currently, I am utilizing the jQuery function load() with the code snippet $('#result').load('http://.... #div'); to retrieve the content of an external website. Moreover, I have made modifications to the domain whitelist specifically f ...

How can I toggle a clicked switch in React MUI instead of all switches?

This is the current state in my parent component: const [feedbackType, setFeedbackType] = useState({ manual: true, auto: false, }); I am passing this state as a prop to the child component. In the child component, I have the following code: co ...

When an array object is modified in Vue, it will automatically trigger the get method to validate any

One of the challenges I am facing is related to a button component that has a specific structure: <template> <button class="o-chip border-radius" :class="{ 'background-color-blue': theValue.isSelected, ...

Python AssertionError: The argument passed to the write() function in GAE must be a

Currently, I am utilizing Sublime Text 2 as my primary editor to develop a brand new Google App Engine project. UPDATE: While testing this code via localhost, I encountered an issue when accessing the app on appspot: Status: 500 Internal Server Error ...

Error: The fetch request was unsuccessful [NextJS API]

I keep encountering an error - TypeError: fetch failed after waiting for 300 seconds while requesting an optimization server that requires a response time longer than 300 seconds. The request is being sent from the provided API in NextJS. Is there a way ...

Guide for implementing a one-line if statement in Javascript

I am aiming to assign a class using a single-line if statement as outlined in this source. Currently, I am utilizing Material-UI and attempting to specify a class. Therefore, I would like to implement this approach: if(condition) expression <Typogr ...

Using PhpStorm to update a URL after modifying the DocumentRoot

Currently, I am working on a Laravel 8 project with my DocumentRoot set to the public folder. When I enter http://localhost/ in my browser, it displays the contents of the public folder due to my webserver setup. In PhpStorm, I added this folder as a Res ...

Download an image file directly from an HTTP response in Laravel using Vue, Axios, and Intervention Image

Currently, I am in the process of setting up a media asset database by utilizing Laravel, Vue, Axios, and Intervention image. One of my main objectives is to allow the user to specify their desired image height and width before proceeding with the download ...