Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Empty Form Field Validation?

  • This topic is empty.
Viewing 15 posts - 1 through 15 (of 58 total)
  • Author
    Posts
  • #159074
    MBM
    Participant

    I have created a form with basic validation :

    if($formValue['forename']=="" || $formValue['surname']=="" || $formValue['username']=="" || $formValue['password']=="" || $formValue['email']=="" ){
    $message = "Missing data - please try again" ;
    header("Location: registration.php?message=$message");

    I want to validate each field individually. Could someone give an example using one of the fields above?

    #159075
    __
    Participant

    I want to validate each field individually.

    Then check each one individually.

    if( $formValue['forename'] =="" ){
        $message = "missing data - please try again";
    }
    if( $formValue['surname'] =="" ){
        $message = "missing data - please try again";
    }
    //  etc. ...
    

    Couple notes:

    1) I’m assuming you want to validate individual fields in different ways. If you’re performing the same test on them (in this case, “not empty”), then you should leave them all grouped.

    2) If you know all of your variables exist (i.e., you’ve already declared them), then you can test if they are empty simply by if( ! $your_variable_name ) …. however,

    3) If you do not know for sure that the variables exist (i.e., they may or may not have been declared already), then you would need to use if( empty( $your_variable_name ) ) …. Otherwise, you would get an error when the variable doesn’t exist.

    4) Your Location header is invalid. You need to provide a fully qualified URL (meaning, scheme and domain name included).

    #159084
    MBM
    Participant
    1. No I just want to check if they are empty
    2. No I have not declared them but if it makes things easier I could
    3. Don’t understand? The registration page with the php and html is named registration.php

    I have made the changes though probably have missed something as I get ‘Please enter your email’ regardless of which field is left blank. If all fields are left blank I want the error message to list :

    Please enter your forename Please enter your surname Please enter your username Please enter your password Please enter your email

    If for example username and password are left blank :

    Please enter your surname Please enter your password

    This is what I have :

    if(isset($_POST['Submit'])){
    if( $formValue['forename'] =="" ){$message = "Please enter your forename";
    header("Location: registration.php?message=$message");}
    if( $formValue['surname'] =="" ){$message = "Please enter your surname";
    header("Location: registration.php?message=$message");}
    if( $formValue['username'] =="" ){$message = "Please enter your username";
    header("Location: registration.php?message=$message");}
    if( $formValue['password'] =="" ){$message = "Please enter your password";
    header("Location: registration.php?message=$message");}
    if( $formValue['email'] =="" ){$message = "Please enter your email";
    header("Location: registration.php?message=$message");}
    $formValue['username']=="" || $formValue['password']=="" || $formValue['email']=="" ){
    else{
    DBConnect();

    #159136
    __
    Participant

    No I just want to check if they are empty

    Alright – but since you want specific error messages, you can’t group them all together.

    No I have not declared them but if it makes things easier I could

    It would prevent possible errors.

    However, how did the form values get into the $formValue array? What I’m getting at with this (and point#3) is that if you have already done something like

    if( isset( $_POST['exmaple'] ) ){ 
        $formValue['example'] = $_POST['example'];
    }
    else{
        $formValue['example'] = null;
    }
    

    …then you have declared them, and there’s no need to worry. If not, then you’d need to check to make sure the variables exist before trying to use them.

    I have made the changes though probably have missed something as I get ‘Please enter your email’ regardless of which field is left blank.

    This is because you’re using the same variable for every error message, and so you will only ever see the last value assigned:

    $myVar = "hello";
    $myVar = "world";  // overwrites "hello"
    print $myVar;      // prints only "world"
    

    If all fields are left blank I want the error message to list

    The best approach is to use an array:

    if( true ){
        $message[] = "message # 1";
    }
    if( true ){
        $message[] = "message # 2";
    }
    if( false ){
        $message[] = "message # 3";
    }
    if( true ){
        $message[] = "message # 4";
    }
    

    then, use implode to combine all the messages into a single string:

    $allMessages = implode( "<br>\n",$message );
    print $allMessages;
    /* prints:
    
    message # 1<br>
    message # 2<br>
    message # 4
    
    */
    
    #159137
    MBM
    Participant

    Before I hack away at the code here’s the php.

    <?php
    session_start();
    include "common.php";
    $message = $_GET['message'];
    //COLLECT POST data
    $formValue=array();
    foreach ($_POST as $key => $value) {
    $formValue[$key] = strip_tags($value);
    
    //Lets register some POST Backs
    //This will allow us to repopulate form fields in the future if needed
    $_SESSION['post_vars'][$key] = $value;
    }//close for loop
    if(isset($_POST['Submit'])){
    if( $formValue['forename'] =="" ){$message = "Please enter your forename";
    header("Location: registration.php?message=$message");}
    if( $formValue['surname'] =="" ){$message = "Please enter your surname";
    header("Location: registration.php?message=$message");}
    if( $formValue['username'] =="" ){$message = "Please enter your username";
    header("Location: registration.php?message=$message");}
    if( $formValue['password'] =="" ){$message = "Please enter your password";
    header("Location: registration.php?message=$message");}
    if( $formValue['email'] =="" ){$message = "Please enter your email";
    header("Location: registration.php?message=$message");}
    else{
    DBConnect();
    $Link = mysql_connect($Host, $User, $Password);
    $Query = "INSERT INTO $Table_2 VALUES ('0', '".mysql_escape_string($formValue['forename'])."','".mysql_escape_string($formValue['surname'])."',
    '".mysql_escape_string($formValue['username'])."','".mysql_escape_string($formValue["password"])."', '".mysql_escape_string($formValue["email"])."')";
    if(mysql_db_query ($DBName, $Query, $Link)){
    $message = "You have successfully registered. You may now login";
    header("Location: registration.php?message=$message");
    }else{
    $message = "Error Inserting";
    header("Location: registration.php?message=$message");
        }//close db query conditional
    }//close form validation conditional
        }//close form submit conditional
    ?>
    
    #159141
    __
    Participant

    My posts aren’t showing up. Please follow:

    https://gist.github.com/customanything/8137029

    #159241
    MBM
    Participant

    I had the same problem re my posts. I think you cannot post large chunks of code.

    Thanks for the code. I appreciate the effort. I’m trying to understand it. It’s a lot to take in.

    I tried your code but do not see any error messages for empty fields nor is any data stored in the database.

    I renamed the page register.php and changed the references accordingly. I used the full path to the header location.

    Doesn’t $errMessage have to be declared?

    I entered my details in here :

    $db = new mysqli( “db host”,”username”,”password”,”db name” );

    and removed the slashes here :

    // exit( $db->connect_error );

    It doesn’t show any errors so I’m guessing it connects though I don’t understand why you have used this as my common.php file connects to the database?

    I’ve made a pen with the html and css just incase there are errors in how I have incorporated the form.

    http://codepen.io/MBM/pen/osBqC

    #159271
    MBM
    Participant

    I want to use the first approach you listed. I have messages for each field. They work as you said i.e. I only see the last value assigned.

    if($formValue['forename']==""){
    $message = "Please enter your forename" ;
    header("Location: register.php?message=$message");
    }elseif($formValue['surname']==""){
    $message = "Please enter your surname" ;
    header("Location: register.php?message=$message");
    

    How do I use implode? I tried :

    $allMessages = implode ($message);
    

    then after the form :

    <p class="phpmessage"><?php print $allMessages ; ?></p>
    
    #159284
    __
    Participant

    It doesn’t show any errors so I’m guessing it connects though I don’t understand why you have used this as my common.php file connects to the database?

    I used mysqli simply to show you an alternative to the mysql_* functions. As I said, ext/mysql is long deprecated, and I highly recommend switching to mysqli or PDO. Of course, it’s up to you; ext/mysql will continue to function for some time. You just won’t get as good performance, and you need to be more careful about security.

    Doesn’t $errMessage have to be declared?

    In spots like this:

    $errMessage[] = "Please enter your forename";
    

    No; you’re declaring it right then, as you assign the value.

    This, however:

    if( $errMessage ){
    

    should be

    if( ! empty( $errMessage ) ){
    

    …because $errMessge may or may not have been declared.

    I tried your code but do not see any error messages for empty fields

    Another typo (sorry):

    header( "Location: http://example.com/registeration.php?message=$message" );
    // SHOULD be:
    header( "Location: http://example.com/registeration.php?message=$errMessage" );
    

    nor is any data stored in the database.

    I assume you mean “…when valid entries are provided.” I wouldn’t know for sure. When you provide valid entries, are you redirected to the success or error message? Have you un-commented the MySQL error messages?

    The most obvious spot where there might be a problem is in the SQL statement, since I don’t actually know the names of the columns in your database.

    #159286
    __
    Participant

    How do I use implode? I tried :

    $allMessages = implode ($message);

    implode operates on an array. In your example, $message is a string, so it will throw an error. If you don’t see any errors, then you need to enable error reporting (turn it off again when your site is ready to go “live”). In your php.ini file, do:

    error_reporting = E_ALL | E_STRICT
    display_errors = on
    

    (The | E_STRICT part is only necessary before php 5.4.)

    More php error reporting info.

    To learn how to use impode (or any function), read the manual. implode takes two arguments: “glue” (character(s) to separate each string) and “pieces” (an array of strings). So, make each of your error messages an item in an array, not a string by itself:

    // no
    // $message = "my message";
    // $message = "another message";
    
    // yes
    $message[] = "my message";
    $message[] = "another message";
    

    For glue, I would suggest a <br> element, so each message will appear on its own line:

    $allMessages = implode( "<br>",$message );
    
    #159329
    MBM
    Participant

    Error reporting is on in my common.php file. It’s still not working.

    <?php
    session_start();
    include "common.php";
    $message = $_GET['message'];
    //COLLECT POST data
    $formValue=array();
    foreach ($_POST as $key => $value) {
    $formValue[$key] = strip_tags($value);
    $allmessages = implode( "<br>",$message );

    if($formValue['forename']==""){
    $message[] = "Please enter your forename" ;

    etc, etc

    Then after the form :

    <p class="phpmessage"><?php print $allmessages ; ?></p>

    I also tried print $message.

    #159330
    MBM
    Participant

    What I find annoying is that there seem to be many differents ways to do the same thing in php and it’s very confusing.

    I’m not concerned about security at the moment as I’m only learning php for my studies and for recreational use.

    Want I want to be able to do is :

    1. Capture data in a form
    2. Validate the data in a form
    3. Display the data in a form
    4. Allow users to edit their data

    1 & 3 I can do. 2. You’ve pointed me in the right direction and I’m guessing there’s an error in my syntax

    One I can validate the data and edit the data I’ll take a look at mysqli.

    #159332
    __
    Participant

    Error reporting is on in my common.php file. It’s still not working.

    Okay: let’s clarify what you mean by that. “Not working” is too nonspecific to be helpful. What is happening? I would expect one of:

    • redirected to your registration page, with error message(s) in query string

    • redirected to registration page, with success message

    • redirected to registration page, with failure message

    • php error messages

    • mysql error messages

    • blank page

    #159333
    MBM
    Participant

    Sorry. The form is displayed. I can add new records. When I leave a field blank no error messages are displayed. In the url address bar I get :

    register.php?message=

    #159334
    __
    Participant

    When I leave a field blank no error messages are displayed. In the url address bar I get :
    register.php?message=

    Did you notice the typo I mentioned a few posts ago?

    header( "Location: http://example.com/registeration.php?message=$message" );
    // SHOULD be:
    header( "Location: http://example.com/registeration.php?message=$errMessage" );
    
Viewing 15 posts - 1 through 15 (of 58 total)
  • The forum ‘Back End’ is closed to new topics and replies.