【问题标题】:What causes the data validation failure in this Laravel and Vue application? [closed]是什么导致了这个 Laravel 和 Vue 应用程序中的数据验证失败? [关闭]
【发布时间】:2022-01-20 10:00:21
【问题描述】:

我正在开发一个由 Laravel 8 API 和 Vue 3 前端组成的应用程序。

我有一个验证失败的注册表单。

users 表迁移文件中我有:

class CreateUsersTable extends Migration {
 public function up() {
  Schema::create('users', function (Blueprint $table) {
      $table->id();
      $table->string('first_name');
      $table->string('last_name');
      $table->string('email')->unique();
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->unsignedInteger('country_id')->nullable();
      $table->foreign('country_id')->references('id')->on('countries');
      $table->rememberToken();
      $table->timestamps();
   });
 }
 // More code here
}

如上可见,countries表中的id是users表中的外键。

我在 AuthController 中有这段代码来注册一个新用户:

类 AuthController 扩展控制器 {

 public function countries()
 {
    return country::all('id', 'name', 'code');
 }
    
 public function register(Request $request) {

 $rules = [
  'first_name' => 'required|string,',
  'last_name' => 'required|string',
  'email' => 'required|email|unique:users,email',
  'password' => 'required|string|confirmed',
  'country_id' => 'required|exists:countries',
  'accept' => 'accepted',
  ];

  $customMessages = [
   'first_name.required' => 'First name is required.',
   'last_name.required' => 'Last name is required.',
   'email.required' => 'A valid email is required.',
   'email.email' => 'The email address you provided is not valid.',
   'password.required' => 'A password is required.',
   'password.confirmed' => 'The passwords do NOT match.',
   'country_id.required' => 'Please choose a country.',
   'accept.accepted' => 'You must accept the terms and conditions.'
];

 $fields = $request->validate($rules, $customMessages);

 $user = User::create([
    'first_name' => $fields['first_name'],
    'last_name' => $fields['last_name'],
    'email' => $fields['email'],
    'password' => bcrypt($fields['password']),
    'country_id' => $fields['country_id']
 ]);

 $token = $user->createToken('secret-token')->plainTextToken;

 $response = [
    'countries' => $this->countries(),
    'user' => $user,
    'token' => $token
 ];

 return response($response, 201);
 }
}

在前端,我有:

const registrationForm = {
    data() {
     return {
      apiUrl: 'http://myapp.test/api',
      formSubmitted: false,
      countries: [],
      fields: {
        first_name: '',
        last_name: '',
        email: '',
        password: '',
        country_id: 0,
        accepted: '',
      },
      errors: {},
    };
  },
  methods: {
    // Select country
    changeCountry(e) {
      if(e.target.options.selectedIndex > -1) {
        this.country_id = parseInt(e.target.options[e.target.options.selectedIndex].value);
      }
    },

    // get Countries
    getCountries(){
      axios.get(`${this.apiUrl}/register`).then((response) =>{
        // Populate countries array
        this.countries = response.data;
      }).catch((error) => {
         this.errors = error.response.data.errors;
      });
    },

    registerUser(){
      // Do Registrarion
      axios.post(`${this.apiUrl}/register`, this.fields).then(() => {
        // Show success message
        this.formSubmitted = true;

        // Clear the fields
        this.fields = {}

      }).catch((error) => {
        this.errors = error.response.data.errors;
      });
    }
  },
  created() {
    this.getCountries();
  }
};

Vue.createApp(registrationForm).mount("#myForm");

在 Vue 模板中:

<form id="myForm">
    <div v-if="formSubmitted" class="alert alert-success alert-dismissible">
      <button type="button" class="close" data-dismiss="alert">&times;</button>
      Your account was created :)
    </div>

    <div class="form-group" :class="{ 'has-error': errors.first_name }">
    <input type="text" class="form-control" placeholder="First name" v-model="fields.first_name">
    <span v-if="errors.first_name" class="error-message">{{ errors.first_name[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.last_name }">
    <input type="text" class="form-control" placeholder="Last name" v-model="fields.last_name">
    <span v-if="errors.last_name" class="error-message">{{ errors.last_name[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.email }">
    <input type="email" class="form-control" placeholder="Enter email" v-model="fields.email">
    <span v-if="errors.email" class="error-message">{{ errors.email[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.password }">
    <input type="password" class="form-control" placeholder="Enter password" v-model="fields.password">
    <span v-if="errors.password" class="error-message">{{ errors.password[0] }}</span>
  </div>

  <div class="form-group" :class="{ 'has-error': errors.password_confirmation }">
    <input type="password" class="form-control" placeholder="Confirm password" v-model="fields.password_confirmation">
    <span v-if="errors.password_confirmation" class="error-message">{{ errors.password_confirmation[0] }}</span>
  </div>

  <div class="form-group">
    <select class="form-control" @change="changeCountry">
       <option value="0" selected>Select your country</option>
       <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
    </select>
  </div>

  <div class="form-group accept pl-1" :class="{ 'has-error': errors.accept }">
    <input type="checkbox" name="accept" v-model="fields.accept">
    <span class="text text-muted pl-1">By creating an account I accept <a href="#" class="text-link">Terms & Privacy Policy</a></span>
    <span v-if="errors && errors.accept" class="error-message">{{ errors.accept[0] }}</span>
  </div>

  <div class="form-group mb-0">
    <button @click.prevent="registerUser" type="submit" class="btn btn-sm btn-success btn-block">Register</button>
  </div>
</form>

问题

我填写了表格,选择了一个国家,但是当我提交时,它以 422 状态失败,并且网络选项卡显示:

{"message":"The given data was invalid.","errors":{"country_id":["The selected country id is invalid."]}}

问题

我做错了什么?

【问题讨论】:

    标签: php laravel vue.js laravel-8


    【解决方案1】:

    你在这里有错误this.country_id(registrationForm 组件),但属性country_idthis.fields 的子级,你将fields 发送到服务器。正确的是:

    this.fields.country_id = parseInt(e.target.options[e.target.options.selectedIndex].value);
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2012-02-27
      • 2015-08-27
      • 2015-03-02
      相关资源
      最近更新 更多