简体   繁体   中英

How to start validating php form only after I clicked submit

I am new to php and web development. I am trying to do a simple validation of text field. I want to display a red remark beside the text field after submit button was clicked.

However my problem here is: The php codes validates all input field the moment the page was loaded. How to validate it only after user clicked the submit button?

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        Name <input type='text' name='name' /><br>
        Email <input type='text' name='email' /><br>
        Age<input type='text' name='age' /><br>
        <input type='submit' name='Done' /><br><br>
</form>

<?php
    if(empty($POST['name']))
        echo '<font color="red">Please enter your name.</font>';
    if(empty($POST['email']))
        echo '<font color="red">Please enter your email.</font>';
    if(empty($POST['age']))
        echo '<font color="red">Please enter your age.</font>';
?>

I have several questions here:

1) If I want to display the error message right beside each text field, shall I write a separate php code beside each input field?

2) How to echo the error message only after user clicked the submit button?

I know this is extremely simply to many people here, but this is my first time doing something related to the web.

Use $_SERVER['REQUEST_METHOD'] to detect whether the page is being displayed in response to posting the form.

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if (empty($_POST['name'])) {
        echo '<span style="color: red;">Please enter your name.</span>';
    }
    if(empty($_POST['email'])) {
        echo '<span style="color: red;">Please enter your email.</span>';
    }
    if(empty($_POST['age'])) {
        echo '<span style="color: red;">Please enter your age.</span>';
    }
}

If you want to show them separately next to each input, you can write:

Name <input type='text' name='name' /> <?php 
if ($_SERVER['REQUEST_METHOD'] == "POST" && empty($_POST['name'])) {
    echo '<span style="color: red;">Please enter your name.</span>';
} ?><br>

Note that the variable containing POST parameters is $_POST , not $POST .

Just check if post is send

<?php
        if($_POST)
        {
            if(empty($POST['name']))
                echo '<font color="red">Please enter your name.</font>';
            if(empty($POST['email']))
                echo '<font color="red">Please enter your email.</font>';
            if(empty($POST['age']))
                echo '<font color="red">Please enter your age.</font>';
        }
    ?>

Please note:

<input type='submit' name='Done' /><br><br>

should be outside the PHP markup. To display the errors beside each element, just move your if statements to the place where it should be displayed in the HTML.

Most developers use javascript for form validation. A quick Google will give you a lot information about this.

try this i used your form working 100% =)

<script>
    function ValidateForm() {
        var name = document.getElementById('name').value;
        var email = document.getElementById('email').value;
        var age = document.getElementById('age').value;
        if (name == "" && email == "" && age == "")
        {
            document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
            document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
            document.getElementById("error_age").innerHTML = "Please enter your age";
            return false;
        }
        else if (name == "")
        {
            document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
            return false;

        }
        else if (email == "")
        {
            document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
            return false;
        }
        else if (age == "")
        {
            document.getElementById("error_age").innerHTML = "Please enter your age";
            return false;
        }
    }
</script>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onSubmit="return ValidateForm()">
    Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"></span> <br>
    Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"></span><br>
    Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"></span><br>
    <input type='submit' name='Done' /><br><br>
</form>

Here is a pure php printing the error right beside the form fields

<?php
    $fieldErrors = array();
    if(isset($_POST['Done']))
    {
        $fields = array('name', 'email', 'age');
        foreach ($fields as $field) 
        {
            if($_POST[$field] == "")
            {
                $fieldErrors[] = $field;
            }
        }
    }

    if(count($fieldErrors) > 0)
        print_r($fieldErrors);
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("name", $fieldErrors)) ? 'Please Enter your name' :''; ?></span> <br>
    Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("email", $fieldErrors)) ? 'Please Enter your email' :''; ?></span><br>
    Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("age", $fieldErrors)) ? 'Please Enter your age' :''; ?></span><br>
    <input type='submit' name='Done' /><br><br>
</form>

To follow the DRY system you can simplify your code a little and make it easy to adjust in case you add more fields to your form in the future. You only have to add your new fieldname(s) to the $fields array. It is also much easier to adjust the HTML in case you want another class or something.

 if(whatever condition you need)
    {
        $fields = array('name', 'email', 'age');
        foreach ( $fields as $field ) {
            if(empty($POST[$field]))
                echo '<font color="red">Please enter your ' . $field . '.</font>';
            }
        }
    }

Just add a hidden input to your form.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        Name <input type='text' name='name' /><br>
        Email <input type='text' name='email' /><br>
        Age<input type='text' name='age' /><br>
        <input type='submit' name='Done' /><br><br>
<input type="hidden" name='form' value='wasSubmited' />
</form>

Then in the PHP script check $_POST :

if ($_POST['form'] == 'wasSubmited') {
 // here you can start to validate your form
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM