0

new to this. my validation code works perfectly.

However, I am trying to get my message to echo under each text field.

I have tried changing the echo to a error message (changing all the echo to $c_errorErr/$c_pass1Err) and then echo $c_errorErr/$c_pass1Err next to the input field and wrapping this in a span class.

However, this method just stops my validation messages from working. Any suggestions

HTML

            <!--                    <div id="first">-->
            <input type="email" id="email" name="email" placeholder="Email Address" value='' required>
            <br>

            <figure>
                <input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password"  maxlength="30" required><!--<span class="error"><?php //echo $c_pass1Err;            ?></span>-->
                <input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err;            ?></span>-->
                <div id="messages"></div>
            </figure>
            <p class="remember_me">
            </p>
            <input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
            <br>
        </form>

PHP

   <?php
        if (isset($_POST['submit'])) {
            $c_email = $_POST['email'];
            $c_pass1 = $_POST['pass1'];
            $c_pass2 = $_POST['pass2'];
            $c_emailErr = $pass1Err = $pass2Err = "";
            //$c_email = $c_pass1 = $c_pass2 = "";
           // Remove all illegal characters from email
           //$c_email = filter_var($c_email, FILTER_SANITIZE_EMAIL);
           //Checking the email address
            if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
                echo  ("<b  id='email'> This is a valid email address </b>");
            } else {
                echo ("<b id='email'> Email is not a valid email address</b>");
            }
        if (strlen($c_pass1) <= '8') {
     echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
        //check passwords
    }elseif ($c_pass1 == $c_pass2) {
                        $q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
                $stmt = mysqli_prepare($dbc, $q);
                //new
                // $stmt = mysqli_prepare($dbc, $insert_c);
                //debugging
                //$stmt = mysqli_prepare($dbc, $insert_c)  or die(mysqli_error($dbc));

                mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
                if ($q) {
                    echo "<script> alert('registration sucessful')</script>";
                }
            } else {
                echo "<b>Oops! Your passwords do not </b>";
            }
        }
        ?>

2 Answers 2

1

Here's my 2-cents worth (no dependencies):

  1. validate with javascript for better usability.
  2. don't echo throughout the php-ing. save the error messages in an array. You can extend the array for every form element you have.
  3. add verification events to form controls after the page loads, rather than cluttering up the html.

This is not intended to be a use-as-is form for your exact needs, since I can't know what those needs are, but I hope it answers your underlying questions.

In this example, any form element with the class "verify-me" will be verified by the JS verifyData function. This function uses the control value as data, and the control name for method of validation. You can add as many elements as you need.

I copied the 'verify-as-you-go' method that you used in the PHP validation, but if you have many form elements, you can use a switch statement similar to the JS way shown here to keep the code tighter.

Hope you find this useful.

<?php
            $password = $c_email = $c_pass1 = $c_pass2 = $email_status = $password_status1 = $password_status2 = "";
            $err_array = array('email_err' => '', 'password_err1' => '', 'password_err2' => '');

        if (isset($_POST['submit'])) {
         $c_email = clean_input($_POST["email"]);
                        if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
                            // email okay
                        } else {
                                $err_array['email_err'] = 'Not a valid email';
                            }
         $c_pass2 = clean_input($_POST["c_pass2"]);         
         $c_pass1 = clean_input($_POST["c_pass1"]);

            if (strlen($c_pass1) <= '8') {  
                $err_array['password_err1'] = "Password must be at least 8 characters";
            } elseif ($c_pass1 == $c_pass2) {
                    // carry on with fucntions
                }   else {
                        $err_array['password_err2'] = "Ooops, passwords don't match";
                    }
        }

    function clean_input($data) {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
    }
    ?>
    <!doctype html>
    <html>
    <title>form validation</title>
    <style type = "text/css">
    .error 
    {
    color: red;
    }
    </style>
    <h1>Form</h1>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
         E-mail: <input type="text" name="email" class = "verify-me" value = "<?=$c_email?>">
         <span class="error"><?php echo $err_array['email_err']; ?></span>
         <br>
         Password: <input type="text" name="c_pass1" class = "verify-me" value = "<?=$c_pass1?>">
         <span class="error"><?php echo $err_array['password_err1']; ?></span>
         <br>
         Password again: <input type="text" name="c_pass2" class = "verify-me" value = "<?=$c_pass2?>">
         <span class="error"><?php echo $err_array['password_err2']; ?></span>
         <br><br>
         <input type="submit" name="submit" value="Submit"> 
    </form>

    </body>
    <script>
        //  set onclick and onchange events for all inputs with className: 'verify-me'
    var verify = document.getElementsByClassName('verify-me');
        for (var i = 0; i < verify.length ; i++)
            {
            verify[i].onclick = function () { resetError( this ); } ;
            verify[i].onchange = function () { verifyData( this, this.name ); } ;
            }
        //  this function to clear the error code when the input is edited 
        function resetError (inputElement) {
            inputElement.nextElementSibling.innerHTML = '';
        }

        //  check the item value, and run a test according to dataType.
        function verifyData(item, dataType) {
            switch (dataType) {

                case 'email':
                if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(item.value)) {
                        console.log('c_pass1 okay');
                    } else {
                        item.nextElementSibling.innerHTML = 'Not a valid email address';
                }
                break;

                case 'c_pass1':
                if (item.value.length >= 8) {
                    console.log('c_pass1 okay');
                } else {
                        item.nextElementSibling.innerHTML = 'Password must be 8 characters or more';
                    }
                break;

                case 'c_pass2':
                if (item.value == document.getElementById('c_pass1.value')) {
                    console.log('c_pass2 okay');
                } else {
                        item.nextElementSibling.innerHTML = 'Passwords do not match';
                    }
                break;
            }
        }
    </script>
    </html>
Sign up to request clarification or add additional context in comments.

Comments

1

I wanted to offer a JS solution on top of your PHP code. For end users, you want real time feedback for them. Posting and being brought back without the original POST data isn't ideal for end users; they get annoyed.

The below is just a sample that you can use to manipulate and make your own. Someone with more JS knowledge could probably clean and streamline the code some more.

As to the PHP solution using your example and code; on error, I don't really see why you're echo'ing your errors. I would save them to your variables and echo the variables. In other words:

if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false)
{
    $c_emailErr = "<b  id='email'> This is a valid email address </b>";
}

Then echo your variable underneath the form field.

The following is a JS solution sample that will display the errors as the user types. I hope this guides you.

function validateEmail(email) {
  var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
  return re.test(email);
}

function verifyPEmail() {
  var pEmail = $("#txtNewEmail").val();

  if (pEmail != "" && validateEmail(pEmail) == false) {
    $("#divCheckValidEmail").html("<span style='color:red;'>Email Structure is Invalid</span>");
  } else if (validateEmail(pEmail) == true) {
    $("#divCheckValidEmail").html("<span style='color:green;'>Valid Email Structure</span>");
  } else if (pEmail == "") {
    $("#divCheckValidEmail").html("<span style='color:red;'>Missing Email</span>");
  }
}

function verifyPass1() {
  var pass1 = $("#pass1").val();

  if (pass1 == "" || pass1.length < 8) {
    $("#divCheckPass1").html("<span style='color:red;'>Password must be at least 8 characters long</span>");
  } else {
    $("#divCheckPass1").html("<span style='color:green;'></span>");
  }
}

function verifyPass2() {
  var pass1 = $("#pass1").val();
  var pass2 = $("#pass2").val();

  if (pass1 !== pass2) {
    $("#divCheckPass2").html("<span style='color:red;'>Password do not match</span>");
  } else {
    $("#divCheckPass2").html("<span style='color:green;'>Passwords Match</span>");
  }
}

$(document).ready(function() {
  $("#txtVerifyEmail").keyup(verifyPEmail);
  $("#pass1").keyup(verifyPass1);
  $("#pass2").keyup(verifyPass2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>

<form action="index.php" name="formInput" method="POST" autocomplete="off">
  <label class="input"><span class="fontBold fontItalic">Email address</span>
    <br>
    <input type="email" name="pgEmail" id="txtNewEmail" oninput="verifyPEmail();" value="">
  </label>
  <div class="registrationFormAlert" id="divCheckValidEmail"></div>

  <label class="input"><span class="fontBold fontItalic">Password</span>
    <br>
    <input type="password" name="pass1" id="pass1" oninput="verifyPass1();" value="">
  </label>
  <div class="registrationFormAlert" id="divCheckPass1"></div>

  <label class="input"><span class="fontBold fontItalic">Verify Password</span>
    <br>
    <input type="password" name="pass2" id="pass2" oninput="verifyPass2();" value="">
  </label>
  <div class="registrationFormAlert" id="divCheckPass2"></div>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.