如果表单字段为空,则显示错误消息,表单未提交

时间:2017-10-16 07:14:12

标签: php json

我正在尝试创建Api。我正在尝试提交表单。表单已提交,表单提交后的响应消息为Ok。但是我试图验证此表单,如果任何字段为空,则表单未提交并显示验证消息。

    <?php
    require('../../../../wp-blog-header.php');
    header("HTTP/1.1 200 OK");
    global $wpdb;
    global $serverUrl;
    global $current_user;
    $id =isset($_REQUEST['store_id']) ? $_REQUEST['store_id'] : '';
    $user_id =isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
    $unit_data = isset($_REQUEST['unit_data']) ? $_REQUEST['unit_data'] : '';
    $product = isset($_REQUEST['product']) ? $_REQUEST['product'] : '';
    $checked_by = isset($_REQUEST['checked_by']) ? $_REQUEST['checked_by'] : '';
    $username = isset($_POST['username']) ? $_POST['username'] : '';
    $option = "signup";

    $data = array(  
            'store_id' =>$id,   
        'user_id' =>$uid,
        'unit_data' =>$unit_data,
            'category_name'=>'delivery_form',
            'checked_by'=>$checked_by,
            'product' =>$product, 
            'suppliers'=>$suppliers,
            'username' =>$username,
        );
    $insert=$wpdb->insert('diary_user_form_storage', $data);
            echo json_encode(
                array(
                    "status" => "1",
                    'user_id' =>  $user->ID,
                                    'message' => 'Data submitted',
                    "token" => $token,      
                    'token' => $token.$device_id.$device_type,
                    'serverUrl' => $serverUrl,  
      $data = array(  
            'store_id' =>$id,   
        'user_id' =>$uid,
        'unit_data' =>$unit_data,   
            'product' =>$product,
           'suppliers'=>$suppliers,
            'checked_by'=>$checked_by,
            'username' =>$username,
            'option'=>$option
        )
        ));
        exit();



 ?>

1 个答案:

答案 0 :(得分:0)

如果你想坚持使用PHP,那就简单了:

if($value == ""){$value_err = "This field is required"};

然后将$ value_err放在需要输入的内容旁边的红色范围内。您也可以使用相同的做法:

$if(value_err == ""){
//Submit Values to Database
}
else{
//Don't
}

提交您的价值观。 您还可以使用JavaScript在您需要验证的其中一个输入上使用onblur动态检查它,然后使用

function checkEmpty(id, idErr){

var z = document.getElementById("myForm");
z.addEventListener("blur", checkEmpty, true);

var x = document.getElementById(id);
var y = document.getElementById(idErr);
if(x.value == ""){
//If direct value
y.value = "This field is required.";
//If inside a span as PHP example above
//y.innerHTML = "This field is required.";
   }
}