Php Form - Проверка ошибок - PullRequest
1 голос
/ 24 июня 2011

Я создал форму онлайн, и когда пользователь нажимает кнопку Отправить, я хочу, чтобы форма проверила на наличие ошибок (т. Е. Отсутствует поле). На данный момент у меня есть форма, проверяющая поля одно за другим, и как только она обнаружит ошибку, она выйдет без проверки остальных полей. Можно ли как-нибудь объединить все операторы if, которые проверяют ошибки, в один.

Вот код

 //Code to check that the Student Name field is completed
    if(empty($_POST['studentName'])) 
    {
    $studentNameError = "You did not enter the student name Wank";
    //echo "<h3> $studentNameError </h3>";
    exit();
    }
    //Code to check that the Tutor Name field is completed
    if(empty($_POST['tutorName'] ))
    {
    echo "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
    exit();
    }
    //Code to check that the Procedure field is completed
    if(empty($_POST['procedure'] ))
    {
    echo  "<h3>You did not select a procedure. Please go back and enter the name of the procedure which you undertook</h3>";
    exit();
    }
    //Code to check that the Grade field is completed
    if(empty($_POST['grade'] ))
    {
    echo "<h3>You did not select a grade. Please go back and select your grade from the drop down list</h3>";
    exit();
    }
    //Code to check that the Student Reflection field is completed
    if(empty($_POST['studentReflection'] ))
    {
    echo "<h3>The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments</h3>";
    exit();
    }
    //Code to check if the tick box is checked that the tutor comment is entered

    if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
    {
        echo "<h3>You must enter a reason why you have clicked the alert box</h3>";
        exit();
    }

Ответы [ 5 ]

0 голосов
/ 24 июня 2011

Например, создайте переменную с именем $status и инициализируйте ее 0, при каждом тесте присваивайте ей 1, если есть ошибка, в конце проверьте, равно ли она единице, выйдите из сценария, в противном случае продолжитевыполнение.Или лучше сделать массив и для каждого теста назначить 0 или 1, зависеть в тесте (поле не пусто, назначить еще один ноль), и позже вы можете отобразить сообщение об ошибке пользователю, указывающее пропущенные поля.

0 голосов
/ 24 июня 2011

Это можно сделать так (один из многих способов - действительно зависит от ваших точных требований к валидации):

<?php
$messages = array();
$errors = 0;

if (empty($_POST['studentName']))
{
    $messages['studentName'] = "You did not enter the student name Wank";
    $errors++;
}
if (empty($_POST['tutorName']))
{
    $messages['tutorName'] = "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
    $errors++;
}

if ($errors) {
    // we have some invalid data in one of the fields
    // display error messages (some feedback to user)
    foreach ($messages as $v) {
        echo $v, "\n";
    }
    exit();
}

// nope, we are fine
// do whatever else is required
0 голосов
/ 24 июня 2011

Есть много способов.Как насчет того, как это, из головы:

$textFieldsThatCannotBeEmpty = array(
    'studentName' => 'You did not enter the student name Wank',
    'tutorName' => 'You did not select a tutor name. Please go back and select your name from the tutors list',
    'procedure' => 'You did not select a procedure. Please go back and enter the name of the procedure which you undertook',
    'grade' => 'You did not select a grade. Please go back and select your grade from the drop down list',
    'studentReflection' => 'The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments'
);

$errors = array();
// check text input fields
foreach($textFieldsThatCannotBeEmpty as $name => $errorMessage){
    if(empty($_POST[$name])){
        $errors[] = $errorMessage;
    }
}
// checkbox
if(!strlen($_POST['tutorComments']) && isset($_POST['alert'])){
    $errors[] = 'You must enter a reason why you have clicked the alert box';
}

if(count($errors) > 0){
    // form is invalid, print errors
    echo '<div class="errors">';
    foreach($errors as $e){
        echo '<h3>',htmlentities($e),'</h3>';
    }
    echo '</div>';
}else{
    // form is valid, let's go and do something with the submitted data
}
0 голосов
/ 24 июня 2011

Поместите все ваши сообщения об ошибках в массив и переберите $ _POST.Если поле ввода пустое, выведите сообщение об ошибке:

<?php
$errorMsgs = array(
  'studentName' => 'You did not enter a student name',
  ...
);

$errors = '';

foreach($_POST as $field)
{
  if(empty($field))
  {
    $errors .= $errorMsgs[$field] . '<br/>';
  }
}

if(strlen($errors))
{
  echo $errors;
  exit();
}
0 голосов
/ 24 июня 2011

Например, вы можете сделать логическую переменную для пометки, если есть ошибка, и выйти, если она истинна + объединить сообщения об ошибках в одно

$error = false;
if(empty($_POST['studentName'])) 
{
$errorMessages[] = "You did not enter the student name Wank";
$error = true;
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errorMessages[] = "You did not select a tutor name. Please go back and select your name from the tutors list";
$error = true;
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errorMessages[] = "You did not select a procedure. Please go back and enter the name of the      procedure which you undertook";
$error = true;
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errorMessages[] ="You did not select a grade. Please go back and select your grade from the drop down list";
$error = true;
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errorMessages[] = "The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments";
$error = true;
}
//Code to check if the tick box is checked that the tutor comment is entered

if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
    $errorMessages[] = "You must enter a reason why you have clicked the alert box";
    $error = true;
}
if($error)
{
    echo("<h3>".implode('<br/>',$errorMessages)."</h3>");
    exit();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...