Jump to content

Validating a form. Cant validate right?


xfire123

Recommended Posts

Hello i have a form with two fields. I used a tutorial for validation. But in my case its not working on 100%.

If i fill only words in the field. The validation work. But after that i add a number validation is passed, and that is not i need.

I need simbols like this: 28-07-2017 or 28/07/2017.

If i fill like this:

28-07-2017 - Passed!

asdasdsd - $from_dateErr = "формат: 0-9 и разделящи символи - и /";

asd28-07-2017 - Passed!

28-07-2017sdfsd - Passed!

 

 

And cant understand the function test_input() what she does in my case.

Here is the code:

<!DOCTYPE html>
<html>
  <head>
  <title>Въвеждане на дата</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>   
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
     <?php

        function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
        }
     // define variables and set to empty values
     $from_dateErr = $to_dateErr =  '';
     $from_date = $to_date = $act = '';
     
        if ($_SERVER["REQUEST_METHOD"] == "GET")
        {
            $valid = true;
            if (empty($_GET["from_date"]) or empty($_GET["to_date"])) {
            $valid = false;
            } else {
                $from_date = test_input($_GET["from_date"]);
                $to_date = test_input($_GET["to_date"]);
                // check if name only contains letters and whitespace
                if (!preg_match("/[0-9\\-]/",$from_date)or !preg_match("/[0-9\\-]/",$to_date)) {
                $from_dateErr = "формат: 0-9 и разделящи символи - и /";
                $to_dateErr = "формат: 0-9 и разделящи символи - и /";
                $valid = false;
                }    
            }
            
  //if valid then action redirect
  if($valid){
    header("location:pagingstatic.php?".$_SERVER['QUERY_STRING']);
   exit();
  }
        }
     ?>
    <div class = "login-box">
        <p class="headp">Test</p>
        <div class = "login">
            <!--
            action = "pagingstatic.php"
            LOGO NEK <div class="image"></div> -->
            <p>Зареждане на таблица от PostgreSQL по зададена дата.</p>
            <form  method = "GET">
                <label for="odata">От дата</label>
                <input type = "text" name = "from_date">
                  <span class="error"><?php echo $from_dateErr;?></span>
                <br />
                <label for="odata">До дата</label>
                <input type = "text" name = "to_date">
                  <span class="error"><?php echo $from_dateErr;?></span>                
                <input type = "submit" name = "submit" value = "Покажи таблица">
            </form>
        </div>
    </div>
      <?php
echo "<h2>Your Input:</h2>";
echo $from_date;
echo "<br>";
echo $to_date;
echo "<br>";
echo $act;
?>
  </body>
</html>
Link to comment
Share on other sites

The test_input() function is nonsense, and you should stay away from whatever tutorial you got it from. We already had a long discussion about similar code yesterday (appearently you guys all read the same tutorials).

 

Leave the input alone. You can check it and reject the request, but do not alter the data. Escaping must happen in the output procedure, and you need to use the right function for the specific context (like htmlspecialchars() for simple HTML contexts).

 

Your data validation doesn't make sense either. You're merely checking of the input contains any digit, backslash (what?) or hyphen, so the application will obviously accept all kinds of strings. A much better approach is to provide a datepicker and not let the user enter arbitrary text in the first place. Then you only have to double-check the input format of the datepicker.

Link to comment
Share on other sites

Yes this is much better option thanks. I used IPerfect v1.0.0

Now i'm wondering how to display error message when submit button is pressed without filled form.

The variables are Null when they are declared and Null after submit button is pressed. In this way always have displayed error text.

Link to comment
Share on other sites

Here is the example:

            // Required field names
        $required = array('from_date', 'to_date');

        // Loop over field names, make sure each one exists and is not empty
        $error = false;
        foreach($required as $field) {
          if (empty($_GET[$field])) {
            $error = true;
          }
        }
        if ($error) {
          echo "All fields are required.";
        } else {
            header("location:gentable.php?".$_SERVER['QUERY_STRING']);
            exit();
        }
     ?>
Link to comment
Share on other sites

No... your validation and use of that validated data should happen in the same script. As mentioned in another thread, validation has a context. You validate differently if the data is going into a database versus a command line versus displayed in javascript or HTML code... So the validation & use need to be a part of the same processing script (not strictly the same PHP file, although you can interpret it that way for now).

 

Honestly, nowadays, I wouldn't even both with the "normal" processing of a form. I'd go straight to jquery & ajax (or something similar).

Link to comment
Share on other sites

You need to stop treating missing parameters and empty parameters equally. There's a big difference between the two. The empty() function is generally a bad choice, because even the string "0" is considered to be “empty”. Use isset() to check for existence and === '' to check for emptiness.

  • If both parameters are missing, you can interpret that as the initial request and simply display the search form.
  • If exactly one parameter is missing, something is wrong. Either there was a problem with the form, or the user has sent an invalid request. You should display an error message.
  • If both parameters exist, you check if they're valid dates. What you do with empty dates is up to you. You can either display an error message or interpret them as “infinite” limits.
Link to comment
Share on other sites

Here's how I basically check my dates in my calendar that I developed for my website (I know shameless plug  :happy-04: ). This hasn't been tested, for I don't use it this way. Which means there might be some modifications that has to be done to the script.

<?php

$myDate = "1964-08-28";

/* Check date is actually a date */
function checkIsAValidDate($myDate) {
    return (bool) strtotime($myDate);
}

$valid = checkIsAValidDate($myDate); // Call the Function:

/* Check to see if date is set, is ten characters in length for a format of 0000-00-00 and is truly a valid date. */
if (isset($myDate) && strlen($myDate) === 10 && $valid) {
    echo "Date is Valid!<br>\n";
}
Link to comment
Share on other sites

The problem with strtotime() is that it accepts a wide range of formats, most of which you hardly expect from the user (like “+10 weeks” or “last Wednesday”). Merely counting the characters doesn't guarentee a specific format either. On top of that, a lot of the date functions and classes allow nonsense dates like “2010-02-31” and silently fix them at the risk of hiding errors.

 

There should be exactly one well-defined format, and you should check it both syntactically (with a regex) and semantically (with something like checkdate()).

Link to comment
Share on other sites

 

You need to stop treating missing parameters and empty parameters equally. There's a big difference between the two. The empty() function is generally a bad choice, because even the string "0" is considered to be “empty”. Use isset() to check for existence and === '' to check for emptiness.

  • If both parameters are missing, you can interpret that as the initial request and simply display the search form.
  • If exactly one parameter is missing, something is wrong. Either there was a problem with the form, or the user has sent an invalid request. You should display an error message.
  • If both parameters exist, you check if they're valid dates. What you do with empty dates is up to you. You can either display an error message or interpret them as “infinite” limits.

 

Im trying to do this but i cant. Do i need to define the variables in the beginning with "" value?

Link to comment
Share on other sites

No, that wouldn't make any sense. What “can't” you do? Show the code and explain the problems.

 Im lost:

    <?php
           
            // Required field names
        $required = array('from_date', 'to_date');

        $error = false;
        if (!isset($required)){
        foreach($required as $field) {
          if (empty($_GET[$field])) {
            $error = true;
          }
        }
        if ($error) {
          $dispErr = "Enter date!";
        } else {
            header("location:gentable.php?".$_SERVER['QUERY_STRING']);
            exit();
        }
        } else {
          $dispErr = "With no message!";  
        }
     ?>

In the first tutorial that you don't like. When i replace POST with GET there i get the same thing - displaying the same validation text on the page after refreshing the page.

Link to comment
Share on other sites

Forget about tutorials and actually think about the code you're writing.

 

You first check if $required isn't set. How, exactly, can it not be set when you've just set in line 4? That seems impossible, doesn't it? Then I've told you how empty() is wrong. And what do you have in your code? empty().

 

Programming isn't about producing random code and then shuffling characters around until it “works”. It's about understanding the problem. So before you write a single line of code, you should have a clear plan of what you want to do. If necessary, write it down, draw a diagram or use pseudo code. Anything that helps you better understand the task.

 

So once again:

  • empty() is bad and doesn't belong into validation code at all. This is not my “opinion”, it's a fact which I've already explained in #12.
  • You need two checks. You first do an isset() check of the input parameter (not some array which you've set yourself). As in
    if (!isset($_POST['a_parameter']))    // if you want to check an URL parameter, then of course you need $_GET instead of $_POST
    {
        // the parameter doesn't exist at all
    }
    
    Then you check if the value of the parameter is an empty string:
    if ($_POST['a_parameter'] === '')
    {
        // the parameter has an empty value
    }
    
    Two checks. First an existence check. Then a check if the value is empty.

As long as you're struggling with the basic concepts, forget about loops and fancy validation schemes. Just do the checks one after another.

Link to comment
Share on other sites

    $dispErr = "";
           

if (isset($_GET['from_date']) && isset($_GET['to_date']))
{
    $dispErr = "";
}

if ($_GET['from_date'] && $_GET['to_date'] === '')
{
    $dispErr = "error";
    header("location:gentable.php?".$_SERVER['QUERY_STRING']);
    exit();
}
   

or

    $dispErr = "";
           

if (!isset($_GET['from_date']) && !isset($_GET['to_date']))
{
    $from_date = $_GET['from_date'];
    $to_date = $_GET['to_date'];
    $dispErr = "error";
}

if ($from_date && $to_date === '')
{
    
    header("location:gentable.php?".$_SERVER['QUERY_STRING']);
    exit();
}

Something like this. Sorry but cant get it...

Link to comment
Share on other sites

You're still in random-code mode.

 

Forget about the code. Close the editor or IDE. Take a piece of paper and write down the necessary steps for one variable. Just one. Don't write actual code, use informal text or pseudo-code.

if parameter "from_date" does not exist, then
    display error: "Missing parameter: from_date"
    -- you could also log this, because a missing parameter may indicate a problem with your form
else if parameter "from_date" has an empty value then
    display: "Please specify the start date"

Do you understand those steps?

Link to comment
Share on other sites

You're still in random-code mode.

 

Forget about the code. Close the editor or IDE. Take a piece of paper and write down the necessary steps for one variable. Just one. Don't write actual code, use informal text or pseudo-code.

if parameter "from_date" does not exist, then
    display error: "Missing parameter: from_date"
    -- you could also log this, because a missing parameter may indicate a problem with your form
else if parameter "from_date" has an empty value then
    display: "Please specify the start date"

Do you understand those steps?

 I think so. I got this:

if ($from_date = !isset($_GET['from_date']) && $to_date = !isset($_GET['to_date']))
{
    $dispErr = "Missing parameter";
} else if ($from_date === '' && $to_date === ''){
    $dispErr = "Please specify the start/end date";
} 
     ?>

After submit i have Notice: Undefined variable: dispErr in  ..  echo code

 

And the message "Missing parameter" come before i hit submit at the first load of the page

Link to comment
Share on other sites

Dude.

 

Stop – writing – random – PHP – code. Stop it. No code. I don't need your code. I need you to start thinking.

 

You said you understand the idea, but you clearly don't, so let's try that again in plain English:

  • You take one parameter at a time. Not two. Not three. One. One parameter.
  • If the parameter doesn't exist, then you display an error message.
  • If it does exist, you check if it's empty. In case of an empty parameter, you display another error message.

That's the procedure for one parameter. Now you have two. A dumb approach would be to randomly try different combinations and hope that one of them is right. You did that, and it failed. The smart approach is to simply do one step after the other: First you validate one parameter, then you validate the next. No combinations. Just a sequence of checks.

 

Do you think you can write pseudo-code (not PHP code) for two checks?

 

Of course this can later be optimized with loops etc., but right now, the goal is to understand the procedure.

Link to comment
Share on other sites

Dude.

 

Stop – writing – random – PHP – code. Stop it. No code. I don't need your code. I need you to start thinking.

 

You said you understand the idea, but you clearly don't, so let's try that again in plain English:

  • You take one parameter at a time. Not two. Not three. One. One parameter.
  • If the parameter doesn't exist, then you display an error message.
  • If it does exist, you check if it's empty. In case of an empty parameter, you display another error message.

That's the procedure for one parameter. Now you have two. A dumb approach would be to randomly try different combinations and hope that one of them is right. You did that, and it failed. The smart approach is to simply do one step after the other: First you validate one parameter, then you validate the next. No combinations. Just a sequence of checks.

 

Do you think you can write pseudo-code (not PHP code) for two checks?

 

Of course this can later be optimized with loops etc., but right now, the goal is to understand the procedure.

Ok i displayed the two errors for the two of the parameters separately. And now what?

Link to comment
Share on other sites

After that i used if statement that check the error variables are equal to "" and then he redirect to the page. I discover this method in the net not by myself :/

btw i don't think its necessary for the user to see the error If the parameter doesn't exist.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.