如何在不刷新或重新加载Vuejs中的页面的情况下启用服务器端验证?

时间:2019-06-26 11:57:21

标签: php vue.js axios server-side-validation

我正在使用v-if=category_toggle隐藏页面上的表格,并使用另一个v-if="add_category_new"显示表单。当我单击提交按钮而不在文本框中输入任何数据时。如果文本框为空,最小长度小于5,最大长度大于45,我想防止刷新页面并启用服务器端验证。这可能吗?我正在将Vue JS与axios一起使用。有人可以帮我解决我的问题吗?这是我的代码

addCategory : function() {
 if(this.category_description.trim() == "" || 
  this.category_description.length < 5 || this.category_description.length 
  > 10) {
this.category_description = "";
this.category_toggle = false;
    this.add_category_new = true;
  }
  else {
axios({
   method : "POST",
   url : this.urlRoot + "admin/add_category.php",
   data : {
    description : this.category_description
   }
}).then(function (response){
       vm.retrieveCategory();
   swal("Congrats!", " New category added!", "success");    
   vm.clearData();          
});
   }
  },

  <?php
  if($_SERVER['REQUEST_METHOD'] == "POST") {
    $validation = new Validation();
    $data = [
        "category_description" => $_POST['category_description'] ?? ''
    ];
    $validation->validate($data, [
        "category_description" => "required|minlen:5|maxlen:45"
    ]);

    $errors = $validation->getErrors();
   } else {
    $data = [
       "category_description" => ""
    ];
    $errors = [
        "category_description" => ""
    ];
   }
  ?>

 <div v-if="add_category_new">
   <div class="profile-head">
      <ul class="nav nav-tabs mt-4" id="myTab" role="tablist">
        <li class="nav-item">
      <a class="nav-link active" id="home-tabs" data-toggle="tab" 
             href="#homes" role="tab" aria-controls="home" aria- 
             selected="true">Add New Category</a>
                </li>
            </ul>
        </div> 
        <div class="row">
          <div class="col-sm-4">   
            <form method="post" @submit="addCategory">
                <div class="form-group">
                  <label for="name"><h6>Category</h6></label>
                  <input type="text" v-model="category_description" name="category_description" value="<?php echo $data['category_description'] ?>" @keydown="isLetter($event)" placeholder="Enter Category" class="form-control <?php if(!empty($errors['category_description'])) { echo 'is-invalid';} ?>">
                  <div class="invalid-feedback"><?php echo $errors['category_description'] ?></div>
                </div>

                <div class="form-group float-left">
                  <div class="input-group">
                      <button type="submit" @click="addCategory" 
   class="btn btn-primary btn-sm"><i class="far fa-save">&nbsp;</i> 
   Save</button>
                  </div>
                </div>
            </form>
          </div>
        </div>
    </div>

0 个答案:

没有答案