Is there a way to successfully submit a form in PHP once it has been validated using JavaScript?

I'm interested in creating a register/login system. I've set up a form in Register.php and handled the validation part in JavaScript, but I'm encountering an issue where no values are being sent to the database upon clicking submit.

Register.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style/regStyle.css">
    <title>Register</title>
</head>
...

and this is Script.js

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');

...

When submitting the form in register.php, I want the validation to occur first and then proceed with submission based on that. What am I doing wrong?

Thank you.

Answer №1

Within your checkLength function, you have overlooked returning the value stored in the error variable. This oversight causes the error to be updated to NaN and subsequently remains stuck at that erroneous state.

function checkLength(input, min, max) {
    let error = 0;

    if (input.value.length < min) {
        showError(input, `${getFieldName(input)} must be at least ${min} characters`);
        error++;
    } else if (input.value.length > max) {
        showError(input, `${getFieldName(input)} must be less than ${max} characters`);
        error++;
    } else {
        showSuccess(input);
    }
    return error;
}

Answer №2

Avoid using the submit event to validate the form and instead utilize the built-in form validation feature. Ensure all required form fields have the attribute required so that the form will only be submitted if all fields are valid.

If you listen for the invalid event, you can display error messages accordingly. Additionally, you can check if a form field is valid when the user inputs data and remove any errors as needed.

The only missing piece is the accurate regular expression for validating email addresses. I included one that I've used before, but it may not validate in the same way as yours does.

document.forms.registration.addEventListener('invalid', e => {
  e.preventDefault();
  e.target.classList.add('invalid');
}, true);

document.forms.registration.addEventListener('input', e => {
  let form = e.target.form;
  if(e.target.validity.valid){
    e.target.classList.remove('invalid');
  }
  if(e.target.name == 'password'){
    form.password2.pattern = `^${e.target.value}$`;
  }
});
small {
  visibility: hidden;
}

input.invalid ~ small {
  visibility: visible;
}
<form name="registration" class="form" action="register.php" method="POST">
  <h2>Register With Us</h2>
  <div class="form-control">
    <label for="username">Username</label>
    <input type="text" name="username" id="username" placeholder="Enter username"
      minlength="3" maxlength="15" required>
    <small>Password must be between 3 and 15 characters.</small>
  </div>
  <div class="form-control">
    <label for="email">Email</label>
    <input type="email" id="email" placeholder="Enter Email" name="email"
     pattern="^[a-z0-9!#$%&'*+\/=?^_`\{\|\}~\-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`\{\|\}~\-]+)*@(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?$" required>
    <small>Email is not valid.</small>
  </div>
  <div class="form-control">
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="Enter password"
      minlength="6" maxlength="25" required>
    <small>Password must be between 6 and 25 characters.</small>
  </div>
  <div class="form-control">
    <label for="password2">Confirm Password </label>
    <input type="password" id="password2" placeholder="Enter password again" required>
    <small>Passwords do not match.</small>
  </div>
  <button type="submit" name="signup">Signup</button>
</form>

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

What is the best method for retrieving values from a FlexiGrid?

I'm having trouble finding information on how to retrieve a cell's value from a flexigrid. My goal is to fetch the value of the third column for every checked item (each row has a checkbox). While I have a function that successfully gets the ro ...

Tips for implementing rtlcss node package with twitter-bootstrap in Laravel framework

Recently, I've delved into using Laravel Mix for compiling SCSS and JS files, and I have a question that's been lingering in my mind. I'm looking to implement rtlcss npm to convert Twitter Bootstrap to right-to-left layout. Below is the def ...

Ways to consistently press a particular button every single second

The code on the webpage looks like this: <div id="content"> <div class="container-fluid"> Slots <p>The current jackpot is 23220!<p/> <p>You lose.</p> <form method=post action=/game ...

What is the best way to differentiate between PHP's callable types?

Is there a way to compare two callable types in order to determine if they are equal or the same? function addCallable(callable $cb) { if(/*check if already exists*/) throw new Exception("Callable was already added to the collection"); els ...

Synchronize Magento cart totals and items using AJAX

Hello there, I am currently developing a custom AJAX cart for Magento and I prefer not to use any pre-made extensions. I want this cart to be unique and tailored specifically to my needs. Could you please advise me on the best method to retrieve importan ...

Save your AngularJS SVG file as a JPG

I am attempting to develop a custom directive that will allow me to convert an SVG file into a JPG or PNG format. I stumbled upon this website: http://bl.ocks.org/mbostock/6466603 So, I decided to try and implement something similar with the following co ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

"Experiencing issues with the Ajax search functionality, need assistance

I am working on a JavaScript code to create search suggestions for a music search engine. The issue I am facing is that when the first character is typed, everything works fine. However, if I type more characters, all the results are displayed in a singl ...

Using PHP to convert JSON data into the Google Chart API

I am facing an issue with parsing my PHP generated JSON array into a Google chart. I have integrated JQuery, but for some reason, I am struggling to parse the JSON data. I execute a MySQL query to fetch data from the database. Then, I encode the query resu ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

The initial io.emit message seems to always be delayed or lost in transmission

io.on('connection',function(socket){ console.log('connected'); socket.on('disconnect',()=>{ console.log('a user disconnected'); }); socket.on('sendMessage',function(data){ const message = data.te ...

Choose a file at random from the folder, assigning probabilities based on the file names

When it comes to font files, they often have names like FontName-type.extension. All these files are stored in a single folder and I currently have this function: function random_font($dir = 'fonts') { $fonts = glob($dir . '/*'); ...

Steps for modifying material-ui timepicker to display time in a 24-hour format

Presently, I am utilizing a Timepicker from material-ui. It is currently configured with type="time", allowing me to select times throughout the day in 12-hour increments with an AM / PM choice. However, I wish to adjust my picker to a 24-hour format, elim ...

Utilize node.js to run a local .php file within a polling loop

Here is the purpose of my application in brief. I am using a PHP file to read data via an ODBC connection and then write that data to a local database. This PHP file needs to be executed LOCALLY ON THE SERVER every time a loop is processed in my node.js, ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file. ConvertFileToAddress(event): string { let localAddress: any; const reader = new FileReader(); reader.readAsDataURL(event.target['files'][0]); reader ...

WordPress presents a challenge with PHP Heredoc not displaying variables in HTML

I've coded some functions in my theme's functions.php file. Here is an example: $usrProfileHTML = <<<EOD <div class="eUserProfile"> <div class="eUsrImage"> <img src="{$envUserProfile['eUsrImage']}" a ...

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...