Hi everyone, here in this code i have inserted javascript form validation and it is working as well, but when i click the submit button for empty fileds it mentions that the filed is empty but at the same time it adds the empty record.. i have checked my code but could not find any error please check it once. any kind of help will be appreciated. thanx :)

<?php include("../includes/pre-header.php");?>

<script type="text/javascript" src="../javascript/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="../javascript/jQuery.validity.min.js"></script>


<script type="text/javascript">
    $(function() {
                $("form").validity(function() {
                    $("#email")
                        .require()
                        .match("email", "Please Type a Valid E-mail address!!")

                    $("#password")
                        .require()
                        .minLength(5, "Your Password must be 5 characters long!!");
                    $("#firstname")
                    .require("This Field Must Be Filled!!")
                    .minlength(6, "Your Name must be 6 characters long!!")
                    .maxlength(20, "Your Name must be less than 20 characters!!")

                    $("#lastname")
                    .require("This Filed Must Be Filled!!")
                    .minlength(6, "Your Name must be 6 characters long!!")
                    .maxlength(20, "Your Name must be less than 20 characters!!")

                });
            });
        </script>
<title>Manage Users</title>
</head>


//here i am inserting just the validation part and form part of the page bcoz code is lenghty


<form method="post" id="form" action="manage-users-action.php">
<label for="email">Email/Username:</label><input id="email" type="text" name="email" value="" class="text" /><br /><br />
<label for="password">Password:</label><input id="password" type="password" name="password" value="" class="text" /><br /><br />
<label for="firstname">First Name:</label><input id="firstname" type="text" name="firstname" value="" class="text" /><br /><br />
<label for="lastname">Last Name:</label><input id="lastname" type="text" name="lastname" value="" class="text" /><br /><br />
<label for="intro">Brief Introduction:</label><br /><textarea name="intro"> </textarea><br /><br />
<label for="qualification">Qualification</label><br /><textarea name="qualification"></textarea><br /><br />
<label for="image">Profile Image</label><input type="file" name="image" value="" /><br /><br />
<label>Type:</label><br />
<input type="radio" name="type" value="S" checked />Student <br /> <br />
<input type="radio" name="type" value="T" />Teacher<br /><br />
<input type="submit" name="submit"  value="Submit" class="button" />
</form>

this is manage-users-action.php

<?php include("../includes/config.php");?>
<?php
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$type=$_POST['type'];
$email=$_POST['email'];
$pwd=$_POST['password'];
$image=$_FILES['image'];
$intro=$_POST['intro'];
$qualification=$_POST['qualification'];
$recoverykey=md5(time());
$encpwd=md5($pwd);
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);

$check= mysql_query("SELECT email FROM accounts WHERE (email='".$email."')");
$result = mysql_num_rows($check);
if($result !== 0)
{
echo header("Location:manage-users.php?status=3");
}
else
{    
  $sql=("INSERT INTO accounts VALUES (NULL,'".$email."','".$encpwd."','".$fname."','".$lname."','".$type."','".$recoverykey."','".$image."','".$intro."','".$qualification."')");
  if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  } 
echo  header("Location:manage-users.php?status=1");

}

exit();
mysql_close($con);
?>

Dani AI

Generated

Short diagnosis and context: the symptoms (validation messages showing but the empty record still inserted) point to one of two things: the client-side script never prevents the submit event (so the browser posts anyway), or the server accepts empty values because there’s no backend check. This aligns with suggestions from (prevent submission), (inspect $_POST), (JS may error and abort), and (always validate on server).

Common quick causes to check first: a JavaScript exception stops the validation chain (check the browser console), the validation plugin is loaded before jQuery, the plugin method names/casing are inconsistent (that will throw), the submit handler doesn’t call preventDefault/return false, the file input needs enctype="multipart/form-data", or the server-side script inserts without checking for empties.

Minimal client-side guard (won’t rely on plugin internals):

$('#form').on('submit', function(e){
  var email = $.trim($('#email').val());
  var pwd   = $.trim($('#password').val());
  if (!email || !pwd) {
    e.preventDefault();
    $('#email').focus();
    return false;
  }
});

Server-side must always validate and use parameterized queries. Example approach using PDO and current password hashing:

<?php
if (empty($_POST['email']) || empty($_POST['password'])) {
  header('Location: manage-users.php?status=2'); exit;
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
  header('Location: manage-users.php?status=3'); exit;
}
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$pdo = new PDO('mysql:host=HOST;dbname=DB;charset=utf8mb4', 'USER', 'PASS', [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('INSERT INTO accounts (email,password,firstname,lastname,type,recoverykey,intro,qualification,image) VALUES (?,?,?,?,?,?,?,?,?)');
$stmt->execute([$_POST['email'],$hash,$_POST['firstname'],$_POST['lastname'],$_POST['type'],md5(time()),$_POST['intro'],$_POST['qualification'], null]);
header('Location: manage-users.php?status=1'); exit;
?>

Debug checklist (in order): open the browser console and fix any JS errors; temporarily add var_dump($POST) then die() as suggested; disable JS to see what the server receives; ensure form has enctype for file uploads; ensure plugin is loaded after jQuery and that validation method names are correct; replace deprecated mysql* code with prepared statements and enforce server-side checks.

Recommended Answers

All 5 Replies

Clicking the submit button does not stop from posting the info to your php file. You'll need to add some JavaScript valid function, which returns false to stop it.

but i hae used the same javascript in a lot of my pages and they are working perfectly alrite..

Put the snippets below before any scripts in your manage-users-action.php file,
if the array shows and empty email, password, firstname, and lastname, then your javscript might be the problem. Then, we can assume that your javascript's not working properly.

// Add var_dump($_POST);
var_dump($_POST); die();

Looking at the code, I guess you shouldn't provide the "value" attribute unless you placed something other than an empty string. I'm not sure if that would help though.

Another tip, it's a best practice to always validate required fields on your backend. It is not safe to just put your validations via client side.

if your js errors out before it fails than your page would post anyway

is a mesg required here? your code:

 $("#email")
    .require()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.