skip to Main Content

i want to create a register/login system and i create form in Register.php and i make the validation part goes to JavaScript code but the problem i had is that when i click on submit there is no values goes into the database.

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>
<body>
    <div class="container">
        <form id="form"  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">
                <small> Error message </small>
            </div>
            <div class="form-control">
                <label for="email">Email</label>
                <input type="text" id="email" placeholder="Enter Email" name="email">
                <small>Error Message</small>
            </div>
            <div class="form-control">
                <label for="password" >Password</label>
                <input type="password" name ="password" id="password" placeholder="Enter password">
                <small>Error message</small>
            </div>
            <div class="form-control">
                <label for="password2">Confirm Password </label>
                <input type="password" id="password2" placeholder="Enter password again">
                <small>Error message</small>
            </div>
            <button type="submit" name="signup">Signup</button>

        </form>
    </div>

    <script src="script.js"></script>
</body>
</html>

<<?php
 
if(isset($_POST["signup"])) {

    require("connection.php");

    try {
        $username = $_POST["username"];
        $email = $_POST["email"];
        $password = $_POST["password"];

        // Sanitize and validate your inputs here

        // Hash the password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $db->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $hashedPassword);
        $stmt->execute();   

        // Redirect or inform the user of successful registration
    } catch (PDOException $e) {
        // Handle your error here
        echo "Error: " . $e->getMessage();
    }

    $db = null;
}
?>

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');

form.addEventListener('submit', function (e) {
    if (e.submitter && e.submitter.name === "signup") {
        e.preventDefault();
        let allErrors = 0;
        allErrors += checkRequired([username, email, password, password2]);
        allErrors += checkLength(username, 3, 15);
        allErrors += checkLength(password, 6, 25);
        allErrors += checkEmail(email);
        allErrors += checkPasswordMatch(password, password2);
    
        if (allErrors == 0) {
            form.submit();   
        }
    }
});


function showError(input, message) {
    const formControl = input.parentElement;
    formControl.className = 'form-control error';
    const small = formControl.querySelector('small');
    small.innerText = message;
}


function showSuccess(input) {
    const formControl = input.parentElement;
    formControl.className = 'form-control success';
}

function checkRequired(inputArr) {
    let error = 0;

    inputArr.forEach(function (input) {
        if (!input.value || input.value.trim() === '') {
            showError(input, `${getFieldName(input)} is required`);
            ++error;
        } else {
            showSuccess(input);
        }
    });

    return error;
}

function getFieldName(input) {
    return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

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);
    }
}

function checkEmail(input) {

    let error = 0;
    const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0.9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    if (re.test(input.value.trim())) {
        showSuccess(input);
    } else {
        showError(input, 'Email is not valid');
        ++error;
    }
    return error;
}

function checkPasswordMatch(input1, input2) {
    let error = 0;
    if (input1.value !== input2.value) {
        showError(input2, 'Passwords do not match');
        ++error;
    }
    return error;
}

i want when the user click on submit button in the regiser.php the validation happens and according to that it will submit or not.. what i did it wrong?

thank you.

2

Answers


  1. In your checkLength function you’re not returning the error value. This is causing error to update to NaN and is never changing from that value.

    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;
    }
    
    Login or Signup to reply.
  2. Don’t use the submit event for validating the form. Instead, use the build in form validation. All required form fields should have the attribute required. The form will only submit if all the form fields are valid.

    If you listen for the invalid event you can show the error message based on that. And when the user inputs something, you can test if the form field is valid and remove the error again.

    The only thing missing is the correct regular expression for the email. I inserted one that I used before, but it doesn’t validate the same way as yours.

    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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search