Ir para conteúdo
Fórum Script Brasil
  • 0

Mensagem de erro ao voltar página - parte II


Edu Valente

Pergunta

Boa noite a todos. Eu gostaria de pedir uma solução para o problema da mensagem de validação que aparece quando se retorna uma página mesmo que os dados inseridos estejam corretos. O que acontece quando o usuário aperta no botão para retornar uma página no que diz respeito ao PHP e essas mensagens de validação que aparecem indevidamente. Existe uma solução definitiva pra isso? por exemplo: "faz isso que quando você pedir para retornar,

a mensagem de validação não vai mais aparecer." Muito obrigado pelo esclarecimento. Segue abaixo o cód. bugado:

index.php

<?php

if (empty($_POST['action'])) {
    $action = 'start_app';
} else {
    $action =  $_POST['action'];    
}

switch ($action) {
    case 'start_app':

        // set default invoice date 1 month prior to current date
        $interval = new DateInterval('P1M');
        $default_date = new DateTime();
        $default_date->sub($interval);
        $invoice_date_s = $default_date->format('m/d/Y');

        // set default due date 2 months after current date
        $interval = new DateInterval('P2M');
        $default_date = new DateTime();
        $default_date->add($interval);
        $due_date_s = $default_date->format('m/d/Y');

        $message = 'Enter two dates and click on the Submit button.';
        break;
    case 'process_data':
        
        $message = '';
        $invoice_date_s = $_POST['invoice_date'];
        $due_date_s = $_POST['due_date'];

        $invoice_date_ex = explode('/', $invoice_date_s);
        $invoice_date_im = implode('', $invoice_date_ex);
        
        $due_date_ex = explode('/', $due_date_s);
        $due_date_im = implode('', $due_date_ex);
        
        
        // make sure the user enters both dates
        if(empty($invoice_date_s))
        {
           $message = 'Please fill in the first field';
        }
        else if(empty($due_date_s))
        {
          $message = 'Please fill in the second field';    
        }
        else if(strpos($invoice_date_s, '/', 1) != 2 || strpos($invoice_date_s, '/', 4) != 5 || 
                strpos($due_date_s, '/', 1) != 2 || strpos($due_date_s, '/', 4) != 5 ||
                strlen($invoice_date_im) != 8 || strlen($due_date_im) != 8)
        {
           $message = 'Please enter the dates with the format mm/dd/yyyy';    
        }
        
        // the year limit is 2012
        else if($invoice_date_ex[2] > 2020 || $invoice_date_ex[2] < 2011 || $due_date_ex[2] > 2020 || $due_date_ex[2] < 2011)
        {
           $message = 'Enter a year with the format yyyy between 2011 and 2020';    
        }
    
        // convert date strings to DateTime objects
        // and use a try/catch to make sure the dates are valid
      else{   
        try{
          $invoice_date = new DateTime($invoice_date_s);
          $due_date = new DateTime($due_date_s);    
        }
        catch(Exception $e)
        {
         ?>  
          <p style = "font-weight: bold; font-size: 16px;"><?php echo 'Error: Enter valid dates inside the fields.'; ?></p>
         <?php 
           exit(1);    
        }
        // make sure the due date is after the invoice date
        if($invoice_date > $due_date)
        {
           $message = 'The due date must be later the invoice date';    
        }
        // format both dates
        $invoice_date_f = $invoice_date->format('M d, Y');
        $due_date_f = $due_date->format('M d, Y');
        // get the current date and time and format it
        $now = new DateTime();
        $current_date_f = $now->format('M d, Y');
        $current_time_f = $now->format('H:i:s a');
        // get the amount of time between the current date and the due date
        // and format the due date message
        if($due_date > $now)
        {
           $dateInterval = $now->diff($due_date);
           $due_date_message = 'this invoice is due in ' . $dateInterval->format('%y years, %m months and %d days') . '.';    
        }
        else if($due_date <= $now)
        {
           $dateInterval = $due_date->diff($invoice_date);
           $due_date_message = 'this invoice is ' . $dateInterval->format('%y years, %m months and %d days') . ' overdue.';     
        }
       }
        break;
}
include 'date_tester.php';
?>
date_tester.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Date Tester</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
        <h1>Date Tester</h1>
        <form action="." method="post">
        <input type="hidden" name="action" value="process_data"/>

        <label>Invoice Date:</label>
        <input type="text" name="invoice_date"
               value="<?php echo htmlspecialchars($invoice_date_s); ?>"/>
        <br />

        <label>Due Date:</label>
        <input type="text" name="due_date"
               value="<?php echo htmlspecialchars($due_date_s); ?>"/>
        <br />

        <label> </label>
        <input type="submit" value="Submit" />
        <br />

        </form>
        <h2>Message:</h2>
        <?php if ($message != '') : ?>
            
            <p><?php echo $message; ?></p>
        <?php else : ?>
        <table cellspacing="5px">
            <tr>
                <td>Invoice date:</td>
                <td><?php echo $invoice_date_f; ?></td>
            </tr>
            <tr>
                <td>Due date:</td>
                <td><?php echo $due_date_f; ?></td>
            </tr>
            <tr>
                <td>Current date:</td>
                <td><?php echo $current_date_f; ?></td>
            </tr>
            <tr>
                <td>Current time:</td>
                <td><?php echo $current_time_f; ?></td>
            </tr>
            <tr>
                <td>Due date message:</td>
                <td><?php echo $due_date_message; ?></td>
            </tr>
        </table>
        <?php endif; ?>

    </div>
</body>
</html>
main.css
body {
    font-family: Arial, Helvetica, sans-serif;
}
#content {
    width: 450px;
    margin: 0 auto;
    padding: 20px 20px 30px;
    background: white;
    border: 2px solid navy;
}
h1 {
    color: navy;
}
h2 {
    margin: 0;
    padding: .25em 0;
}
p {
    margin: 0;
}
label {
    width: 8em;
    float: left;
    margin-right: 1em;
    margin-bottom: .25em;
}

input {
    float: left;
    margin-bottom: .2em;
}

br {
    clear: both;
}

Editado por Edu Valente
Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0
O que?

Tudo funciona corretamente ao executar a aplicação porém, uma mensagem de erro pedindo para inserir a data no formato mm/dd/yyyy aparece quando o usuário clica no botão "retornar" no browser e não sei o porquê que isso acontece. Já tentei algumas alterações no cód. mas a mensagem de erro continua aparecendo quando clico no botão de "retornar".

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...