如何使这些领域的一些强制性(PHP)?

时间:2014-04-20 22:32:09

标签: php

我正在尝试自定义php脚本以使其适应我的需求 这是代码:

<?php
if (isset($_POST['email']))
{
    $error = '';

    $name = $_POST['name'];
    $email = $_POST['email'];

    if($name=='' || $email=='')
    {
        $error = 'Name and email are mandatory';
    }

    if ($error == '')
    {
        $custom_field1 = $_POST['custom_field1'];
        $custom_field2 = $_POST['custom_field2'];
        $custom_field3 = $_POST['custom_field3'];
        $boolean = 'true';

        $postdata = http_build_query(
            array(
            'name' => $name,
            'email' => $email,
            'custom_field1' => $custom_field1,
            'custom_field2' => $custom_field2,
            'custom_field3' => $custom_field3,
            'list' => $list,
            'boolean' => 'true'
            )
        );

        $opts = array('http' => array('method'  => 'POST', 'header'  => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
        $context  = stream_context_create($opts);
        $result = file_get_contents($app_url.'/signin', false, $context);

        if ($result != 1)
            $error = $result;
    }
} 
?>

默认情况下,名称和电子邮件是两个必填字段,我希望自定义字段1&amp; 2也是强制性的。

我还希望错误消息特定于丢失的字段。 使用当前代码,即使名称已填充,消息也会显示:

  

姓名和电子邮件是强制性的

由于

4 个答案:

答案 0 :(得分:1)

试试这个:

    $name = $_POST['name'];
    $email = $_POST['email'];
    $custom_field1 = $_POST['custom_field1'];
    $custom_field2 = $_POST['custom_field2'];
    $error = array();

    if($name=='')
    {
        $error[] = 'Name are mandatory';
    }

    if($email == '')
    {
        $error[] = 'Email are mandatory';
    }

    if($custom_field1 == '')
    {
        $error[] = 'Custom field 1 is mandatory';
    }

    if($custom_field2 == '')
    {
        $error[] = 'Custom field 2 is mandatory';
    }

    if (!empty($error))
    {
        $custom_field3 = $_POST['custom_field3'];
        $boolean = 'true';

        $postdata = http_build_query(
            array(
            'name' => $name,
            'email' => $email,
            'custom_field1' => $custom_field1,
            'custom_field2' => $custom_field2,
            'custom_field3' => $custom_field3,
            'list' => $list,
            'boolean' => 'true'
            )
        );

        $opts = array('http' => array('method'  => 'POST', 'header'  => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
        $context  = stream_context_create($opts);
        $result = file_get_contents($app_url.'/signin', false, $context);

        if ($result != 1)
            $error[] = $result;
    }
}

当您显示错误消息时,请在$error数组

中进行循环
foreach ($error as $errstr)
{
    echo "<p>{$errstr}</p>";
}

implode为字符串和回声,如

echo "<p>" . implode("</p><p>", $error) . "</p>";

答案 1 :(得分:0)

此块显示if名称为空||(或)电子邮件为空error为&#34;姓名和电子邮件是强制性的&#34;。

if($name=='' || $email=='') {
    $error = 'Name and email are mandatory';
}

如果您想创建单独的错误消息,请按照此模式进行操作。如果你试一试,我相信你会弄清楚的。

答案 2 :(得分:0)

您可以针对您要检查的每个字段制作一个包含自定义错误的if语句:

if ($name == '')
{
    $error = 'Name is mandatory';
}

您可以为要检查的每个字段重复此模式。在进行此检查之前,您需要指定$custom_field1$custom_field2(您的脚本在检查后在两行上执行此操作以确保$error为空)。

您可能需要阅读有关variablesif statement的PHP手册。

答案 3 :(得分:-2)

最简单的解决方案是创建一个包含所需字段的数组并循环它们。这使您能够以灵活的方式检查必填字段包含各个字段的错误消息:

// required fields
$required = [
    'name' => 'Name',
    'email' => 'Emailaddress',
    'custom_field1' => 'My awesome field 1',
    'custom_field2' => 'My awesome field 2',
];

// list of errors
$errors = [];

if (isset($_POST['email'])) {
    // loop through required fields
    foreach ($required as $key => $name) {
        if ($_POST[$key] !== '') {
            continue;
        }

        $errors[$key] = $name . ' is required';
    }
}

// check if there were errors
if (!empty($errors)) {
    // display errors
}

此解决方案的优点是,只需将其添加到$required数组即可轻松添加更多必填字段。

您甚至可以轻松添加其他类似的验证。例如:

// validation of fields
$validation= [
    'name' => [
        'name' => 'Name',
        'required' => true,
    ],
    'email' => [
        'name' => 'Emailaddress',
        'required' => true,
        'validation' => 'email',
    ],
    'custom_field1' => [
        'name' => 'My awesome field 1',
        'required' => true,
        'validation' => '/^[a-z]{2,}$/i',
     ],
    'custom_field2' => [
        'name' => 'My awesome field 2',
        'required' => true,
    ],
];

function validateEmail($key, $data, $errors) {
    if (!filter_var($_POST[$key], FILTER_VALIDATE_EMAIL)) {
        $errors[$key] = $data['name'] . ' must be a valid emailaddress';
    }

    return $errors;
}

function validatePattern($key, $data, $errors) {
    if (preg_match($data['validation'], $_POST[$key]) !== 1) {
        $errors[$key] = $data['name'] . ' has an incorrect format';
    }

    return $errors;
}

// list of errors
$errors = [];

if (isset($_POST['email'])) {
    // loop fields to be validated
    foreach ($validationas $key => $data) {
        if (array_key_exists('validation', $data)) {
            switch($data['validation']) {
                case 'email':
                    $errors = validateEmail($key, $data, $errors);
                    break;

                default:
                    validatePattern($key, $data, $errors)
                    break;
            }
        }

        if ($data['required'] !== true) {
            continue;
        }

        if ($_POST[$key] === '') {
            $errors[$key] = $data['name'] . ' is required';
        }
    }
}

您还可以在LMT-PhD's answer中添加客户端验证,但总是至少具有服务器端验证。客户端验证应被视为对用户而言不仅仅是一件好事。