Skip to content
Advertisement

Input validation – stop form from being clear out

I tried to create a sign up form where I need to validate if the the information entered is already exists in the database.

The code runs fine and can detect if the anything are already exists in the database. The problem is it will clear all the form when it detects anything exists in database.

For example in below picture I try to input an email that already exists in database but in the second photo, all the form fields are clear out

enter image description here

Is there any ways to prevent the form from being cleared out? Its not convenience for user to re-fill the form again.

Below is my code.

<?php 
    include 'include/header.php';
    include ('admin/include/dbcon.php');
  
 ?>
<script type="text/javascript">
$(document).ready(function() {
    $("#inputState3").on('change', function() {
        var val2 = $("#inputState3").val();
        $.ajax({

            url: "stdsec.php",
            method: "post",
            data: 'myvalue=' + val2
        }).done(function(sec) {
            $('#inputState1').html(sec);
        })
    })
});
</script>
<!-- STUDENT FORM SECTION START -->
<section class="Form-bg-image navbar-bottom-space fixNavColor" id="student-form">
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <div class="col-sm-12 my-col">
                    <div class="outerdiv Signup-outerdiv">

                        <h1 class="Login-text">Sign Up</h1>
                        <div class="desc-text">New students on board are required to register to access the student
                            portal. <br> This only takes less than a minute. Already have an account? <a
                                href="studentlogin.php">Log
                                In</a> </div>
                        <hr>

                        <div class="InnerDiv InnerDiv2">
                            <form action="student_signup.php" method="post" enctype="multipart/form-data">
                                <div class="form-row">
                                    <div class="form-group col-md-12">
                                        <input name="fname" title="Please enter your name as per IC." type="text"
                                            class="form-control input-fields" placeholder="First Name" required
                                            id="fullname">
                                        <span class="text-danger" id="fname"></span>
                                    </div>

                                    <div class="form-group col-md-12">
                                        <input name="fficnum" title="Enter IC Number without dashes ( - )." type="text"
                                            class="form-control input-fields" placeholder="IC Number" required
                                            id="std_ic">
                                        <span class="text-danger" id="SICnum"></span>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <input name="pass" title="Please enter your password." type="password"
                                            class="form-control input-fields" placeholder="Your Password" required
                                            id="password">
                                        <span class="text-danger" id="Spassword"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <input name="Cpass" title="Please confirm your password." type="password"
                                            class="form-control input-fields" placeholder="Confirm Password" required
                                            id="cpassword">
                                        <span class="text-danger" id="SCpassword"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <input name="email" title="Please enter your email address." type="email"
                                            class="form-control input-fields" placeholder="Email Address" required
                                            id="email">
                                        <span class="text-danger" id="Semail"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <select name="gender" id="inputState2" class="form-control input-fields"
                                            required="true">
                                            <option value="">Gender</option>
                                            <option value="Male">Male</option>
                                            <option value="Female">Female</option>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <select name="dep" id="inputState3" class="form-control input-fields"
                                            required="true">
                                            <option value="">Department</option>
                                            <?php 
                                            $data = mysqli_query($sql_con,"Select *from departments");
                                            while ($row = mysqli_fetch_array($data)){
                                             ?>
                                            <option value="<?php echo $row['id'] ?>"><?php echo $row['depname'] ?>
                                            </option>
                                            <?php } ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <select name="session" id="inputState1" class="form-control input-fields"
                                            required="true">
                                            <option value="">Session</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <input name="number" type="text" class="form-control input-fields"
                                            placeholder="Contact Number" required id="number">
                                        <span class="text-danger" id="Snumber"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <div class="upload-div">
                                            <input name="img" type="file" class="form-control" id="real-input"
                                                hidden="hidden" required id="img">
                                            <button type="button" id="custom-button">Upload Profile Picture
                                            </button><br class="Br-Hide">
                                            <span id="custom-text">No file chosen</span>
                                        </div>
                                        <span class="text-danger" id="imgerror"></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <input name="address" type="text" class="form-control input-fields"
                                        id="inputAddress" placeholder="Enter Your Address" required>
                                    <span class="text-danger" id="Saddress"></span>
                                </div>
                                <center>
                                    <input name="submit" type="submit" class="btn btn-primary btn-login-form2"
                                        value="Create New Account" onclick="return validate2();">
                                </center>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 
<p data-toggle="modal" data-target="#reg-success" class="forgot-para">Forgot
    Password?</p>
 -->

<!-- STUDENT FORM SECTION END -->

<!-- STUDENT SUCCESSFULL REGISTRATION MODAL DIALOG -->

<div class="modal fade" id="reg-success" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title forgot-heading" id="exampleModalLabel">Registration Success!</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div><br>
            <center><img src="../images/success-icon.svg" width="100" height="100"></center>
            <div class="modal-body text-center">
                <p class="password-errortxt">Congratulations, your account has been successfully created.</p>

                <center>
                    <button name="submit" type="submit" class="btn btn-primary btn-login-form2"
                        onClick="parent.location='studentlogin.php'">Click Here to Login</button>
                </center>

            </div>
        </div>
    </div>
</div>

<?php 
        include('js/customUpload.js');
        include('include/footer.php');
    ?>


<script type="text/javascript">
function validate2() {
    var fname = document.getElementById('full_name').value;
    var std_ic = document.getElementById('std_ic').value;
    var email = document.getElementById('email').value;
    var number = document.getElementById('number').value;
    var address = document.getElementById('inputAddress').value;

    var fnameCheck = /^([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){3,20}$/;
    var std_icCheck = /^(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))([0-9]{2})([0-9]{4})$/;
    var emailCheck = /^([w-.]+@([w-]*.)+[w-]{2,4})?$/;
    var numberCheck = /^(+?6?01)[0-46-9]-*[0-9]{7,8}$/;

    if (fnameCheck.test(fname)) {
        document.getElementById('fname').innerHTML = " ";
    } else {
        document.getElementById('fname').innerHTML = "Invalid Name!";
        return false;

    }
    if (std_icCheck.test(std_ic)) {
        document.getElementById('SICnum').innerHTML = " ";
    } else {
        document.getElementById('SICnum').innerHTML = "Invalid IC Number - Enter IC without dashes (XXXXXXXXXXXX)";
        return false;
    }

    if (emailCheck.test(email)) {
        document.getElementById('Semail').innerHTML = " ";
    } else {
        document.getElementById('Semail').innerHTML = "Invalid Email Address";
        return false;
    }
    if (!isNaN($("number").val())) {} else if (numberCheck.test(number)) {
        document.getElementById('Snumber').innerHTML = " ";
    } else {
        document.getElementById('Snumber').innerHTML = "Invalid phone number.";
        return false;
    }

    if ($('#inputAddress').val().length < 20 || $('#inputAddress').val() == "") {
        document.getElementById('Saddress').innerHTML = "At least 20 characters";
        return false;
    } else {
        document.getElementById('Saddress').innerHTML = " ";
    }
}
</script>

</body>

</html>
<?php 
if (isset($_POST['submit'])) {
    $email = $_POST['email'];
    $data = mysqli_query($sql_con,"select stdemail from students");
    while ($row = mysqli_fetch_array($data)) {
    $emaildb = $row['stdemail'];
    if($emaildb == $email){
        echo "<script>document.getElementById('Semail').innerHTML = '** Email already exist'; </script>";
        exit();
        }
    } 


        $SICnum = $_POST['fficnum'];
        $data = mysqli_query($sql_con,"select std_ic from students");
        while ($row = mysqli_fetch_array($data)) {
        $icnumdb = $row['std_ic'];
        if($icnumdb == $SICnum){
           echo "<script>document.getElementById('SICnum').innerHTML = '** IC already exist'; </script>"; //SICnum = the column ID
            //exit();

            return false;  


            }
        }


    $folder = "suploads/";
    $filename = $_FILES['img']["name"];
    $unique = uniqid().$filename;
    $temname = $_FILES['img']["tmp_name"];
    $size = $_FILES['img']["size"];
    
    $target = $folder.basename($unique);
    $filetype = strtolower(pathinfo($target,PATHINFO_EXTENSION));
    if ($filetype !="jpg" && $filetype !="png" && $filetype !="jpeg") {
        echo "<script>document.getElementById('imgerror').innerHTML = '** File is not an image'; </script>";
        exit();
    }
    else if($size > 2097152){
        echo "<script>document.getElementById('imgerror').innerHTML = '** File is larger than 2MP';</script>";
        exit();
    }
    else {
    move_uploaded_file($temname,$target);
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $SICnum = $_POST['fficnum']; 
    $Cpass = $_POST['Cpass'];
    $email = $_POST['email'];
    $session = $_POST['session'];
    $gender = $_POST['gender']; 
    $depart = $_POST['dep'];
    $number = $_POST['number'];
    $address = $_POST['address'];
    mysqli_query($sql_con,"insert into students (full_name,std_ic,password,stdemail,session,gender,dep,snumber,img,address) values ('$fname','$SICnum','$Cpass','$email','$session','$gender','$depart','$number','$target','$address')");

    echo "<script>$(document).ready(function(){ $('#reg-success').modal('show'); });</script>";
/*    echo "<script>alert('You are successfully registered')</script>"; */

}
}
 ?>

Advertisement

Answer

Use the following code

<?php 
    include 'include/header.php';
    include ('admin/include/dbcon.php');
    $email = "";

 ?>
<script type="text/javascript">
$(document).ready(function() {
    $("#inputState3").on('change', function() {
        var val2 = $("#inputState3").val();
        $.ajax({

            url: "stdsec.php",
            method: "post",
            data: 'myvalue=' + val2
        }).done(function(sec) {
            $('#inputState1').html(sec);
        })
    })
});
</script>
<!-- STUDENT FORM SECTION START -->
<section class="Form-bg-image navbar-bottom-space fixNavColor" id="student-form">
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <div class="col-sm-12 my-col">
                    <div class="outerdiv Signup-outerdiv">

                        <h1 class="Login-text">Sign Up</h1>
                        <div class="desc-text">New students on board are required to register to access the student
                            portal. <br> This only takes less than a minute. Already have an account? <a
                                href="studentlogin.php">Log
                                In</a> </div>
                        <hr>

                        <div class="InnerDiv InnerDiv2">
                            <form action="student_signup.php" method="post" enctype="multipart/form-data">
                                <div class="form-row">
                                    <div class="form-group col-md-12">
                                        <input name="fname" title="Please enter your name as per IC." type="text" value="<?php echo @$_POST['fname']; ?>"
                                            class="form-control input-fields" placeholder="First Name" required
                                            id="fullname">
                                        <span class="text-danger" id="fname"></span>
                                    </div>

                                    <div class="form-group col-md-12">
                                        <input name="fficnum" title="Enter IC Number without dashes ( - )." type="text" value="<?php echo @$_POST['fficnum']; ?>"
                                            class="form-control input-fields" placeholder="IC Number" required
                                            id="std_ic">
                                        <span class="text-danger" id="SICnum"></span>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <input name="pass" title="Please enter your password." type="password" value="<?php echo @$_POST['pass']; ?>"
                                            class="form-control input-fields" placeholder="Your Password" required
                                            id="password">
                                        <span class="text-danger" id="Spassword"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <input name="Cpass" title="Please confirm your password." type="password" value="<?php echo @$_POST['Cpass']; ?>"
                                            class="form-control input-fields" placeholder="Confirm Password" required
                                            id="cpassword">
                                        <span class="text-danger" id="SCpassword"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <input name="email" title="Please enter your email address." type="email" value="<?php echo @$_POST['email']; ?>"
                                            class="form-control input-fields" placeholder="Email Address" required
                                            id="email">
                                        <span class="text-danger" id="Semail"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <select name="gender" id="inputState2" class="form-control input-fields"
                                            required="true">
                                            <option value="">Gender</option>
                                            <option value="Male">Male</option>
                                            <option value="Female">Female</option>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <select name="dep" id="inputState3" class="form-control input-fields"
                                            required="true">
                                            <option value="">Department</option>
                                            <?php 
                                            $data = mysqli_query($sql_con,"Select *from departments");
                                            while ($row = mysqli_fetch_array($data)){
                                             ?>
                                            <option value="<?php echo $row['id'] ?>"><?php echo $row['depname'] ?>
                                            </option>
                                            <?php } ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-6">
                                        <select name="session" id="inputState1" class="form-control input-fields"
                                            required="true">
                                            <option value="">Session</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <input name="number" type="text" value="<?php echo @$_POST['number']; ?>" class="form-control input-fields"
                                            placeholder="Contact Number" required id="number">
                                        <span class="text-danger" id="Snumber"></span>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <div class="upload-div">
                                            <input name="img" type="file" class="form-control" id="real-input" value="<?php echo @$_POST['img']; ?>"
                                                hidden="hidden" required id="img">
                                            <button type="button" id="custom-button">Upload Profile Picture
                                            </button><br class="Br-Hide">
                                            <span id="custom-text">No file chosen</span>
                                        </div>
                                        <span class="text-danger" id="imgerror"></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <input name="address" value="<?php echo @$_POST['address']; ?>" type="text" class="form-control input-fields"
                                        id="inputAddress" placeholder="Enter Your Address" required>
                                    <span class="text-danger" id="Saddress"></span>
                                </div>
                                <center>
                                    <input name="submit" type="submit" class="btn btn-primary btn-login-form2"
                                        value="Create New Account" onclick="return validate2();">
                                </center>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 
<p data-toggle="modal" data-target="#reg-success" class="forgot-para">Forgot
    Password?</p>
 -->

<!-- STUDENT FORM SECTION END -->

<!-- STUDENT SUCCESSFULL REGISTRATION MODAL DIALOG -->

<div class="modal fade" id="reg-success" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title forgot-heading" id="exampleModalLabel">Registration Success!</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div><br>
            <center><img src="../images/success-icon.svg" width="100" height="100"></center>
            <div class="modal-body text-center">
                <p class="password-errortxt">Congratulations, your account has been successfully created.</p>

                <center>
                    <button name="submit" type="submit" class="btn btn-primary btn-login-form2"
                        onClick="parent.location='studentlogin.php'">Click Here to Login</button>
                </center>

            </div>
        </div>
    </div>
</div>

<?php 
        include('js/customUpload.js');
        include('include/footer.php');
    ?>


<script type="text/javascript">
function validate2() {
    var fname = document.getElementById('full_name').value;
    var std_ic = document.getElementById('std_ic').value;
    var email = document.getElementById('email').value;
    var number = document.getElementById('number').value;
    var address = document.getElementById('inputAddress').value;

    var fnameCheck = /^([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){3,20}$/;
    var std_icCheck = /^(([[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))([0-9]{2})([0-9]{4})$/;
    var emailCheck = /^([w-.]+@([w-]*.)+[w-]{2,4})?$/;
    var numberCheck = /^(+?6?01)[0-46-9]-*[0-9]{7,8}$/;

    if (fnameCheck.test(fname)) {
        document.getElementById('fname').innerHTML = " ";
    } else {
        document.getElementById('fname').innerHTML = "Invalid Name!";
        return false;

    }
    if (std_icCheck.test(std_ic)) {
        document.getElementById('SICnum').innerHTML = " ";
    } else {
        document.getElementById('SICnum').innerHTML = "Invalid IC Number - Enter IC without dashes (XXXXXXXXXXXX)";
        return false;
    }

    if (emailCheck.test(email)) {
        document.getElementById('Semail').innerHTML = " ";
    } else {
        document.getElementById('Semail').innerHTML = "Invalid Email Address";
        return false;
    }
    if (!isNaN($("number").val())) {} else if (numberCheck.test(number)) {
        document.getElementById('Snumber').innerHTML = " ";
    } else {
        document.getElementById('Snumber').innerHTML = "Invalid phone number.";
        return false;
    }

    if ($('#inputAddress').val().length < 20 || $('#inputAddress').val() == "") {
        document.getElementById('Saddress').innerHTML = "At least 20 characters";
        return false;
    } else {
        document.getElementById('Saddress').innerHTML = " ";
    }
}
</script>

</body>

</html>
<?php 
if (isset($_POST['submit'])) {
    $email = $_POST['email'];
    $data = mysqli_query($sql_con,"select stdemail from students");
    while ($row = mysqli_fetch_array($data)) {
    $emaildb = $row['stdemail'];
    if($emaildb == $email){
        echo "<script>document.getElementById('Semail').innerHTML = '** Email already exist'; </script>";
        exit();
        }
    } 


        $SICnum = $_POST['fficnum'];
        $data = mysqli_query($sql_con,"select std_ic from students");
        while ($row = mysqli_fetch_array($data)) {
        $icnumdb = $row['std_ic'];
        if($icnumdb == $SICnum){
           echo "<script>document.getElementById('SICnum').innerHTML = '** IC already exist'; </script>"; //SICnum = the column ID
            //exit();

            return false;  


            }
        }


    $folder = "suploads/";
    $filename = $_FILES['img']["name"];
    $unique = uniqid().$filename;
    $temname = $_FILES['img']["tmp_name"];
    $size = $_FILES['img']["size"];
    
    $target = $folder.basename($unique);
    $filetype = strtolower(pathinfo($target,PATHINFO_EXTENSION));
    if ($filetype !="jpg" && $filetype !="png" && $filetype !="jpeg") {
        echo "<script>document.getElementById('imgerror').innerHTML = '** File is not an image'; </script>";
        exit();
    }
    else if($size > 2097152){
        echo "<script>document.getElementById('imgerror').innerHTML = '** File is larger than 2MP';</script>";
        exit();
    }
    else {
    move_uploaded_file($temname,$target);
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $SICnum = $_POST['fficnum']; 
    $Cpass = $_POST['Cpass'];
    $email = $_POST['email'];
    $session = $_POST['session'];
    $gender = $_POST['gender']; 
    $depart = $_POST['dep'];
    $number = $_POST['number'];
    $address = $_POST['address'];
    mysqli_query($sql_con,"insert into students (full_name,std_ic,password,stdemail,session,gender,dep,snumber,img,address) values ('$fname','$SICnum','$Cpass','$email','$session','$gender','$depart','$number','$target','$address')");

    echo "<script>$(document).ready(function(){ $('#reg-success').modal('show'); });</script>";
/*    echo "<script>alert('You are successfully registered')</script>"; */

}
}
 ?>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement