如何在Vue中验证表单?

时间:2018-09-21 09:33:05

标签: javascript vue.js

我想在Vue中建立注册表。

我认为我的书做得还不错。但是我的问题是,如果我使用v-formVuetify中的vue-property-decorator,如何触发验证。

因为所有示例都有this.$refs.form.validate() ...对于这种形式,它不起作用。

那么,提交表单时如何触发验证?

这是我的代码:

<template>

  <v-container fluid fill-height>
    <v-layout align-center justify-center>
      <v-flex xs12 sm8 md6>

        <v-container>
          <v-card>
            <v-toolbar dark color="primary">
              <v-toolbar-title>Register</v-toolbar-title>
            </v-toolbar>
            <v-card-text>

              <v-form v-model="loginValid">

                <v-text-field v-model="form.name.value" prepend-icon="person" name="Name" label="Name" required></v-text-field>
                <v-text-field v-model="form.email.value" :rules="form.email.rule" label="Email" required type="email" prepend-icon="person"></v-text-field>
                <v-text-field prepend-icon="lock" v-model="form.password.value" :rules="form.password.rule" label="Password" type="password" required></v-text-field>
              </v-form>
            </v-card-text>
            <v-card-actions class="pa-3">
              <v-spacer></v-spacer>
              <v-btn ref="btn-entrar" id="btn-entrar" color="primary" @click="submit">Register</v-btn>

              <router-link to="/login" class="btn btn-link">Login</router-link>
            </v-card-actions>

          </v-card>

        </v-container>
      </v-flex>
    </v-layout>
  </v-container>

</template>

<script lang="ts">
import { Component, Watch, Prop } from 'vue-property-decorator';
import BaseComponent from '@/modules/common/components/baseComponent.vue';
import { State, Action, Getter } from 'vuex-class';

@Component({})
export default class RegisterPage extends BaseComponent {
  public loginValid: boolean = false;

  public form = {
    name: { value: '' },
    email: {
      value: '',
      rule: [
        (v: string) => !!v || 'Email is required',
        (v: string) => /.+@.+/.test(v) || 'E-mail must be valid'
      ]
    },
    password: {
      value: '',
      rule: [
        (v: string) => !!v || 'Password is required',
        (v: string) => v.length >= 8 || ''
      ]
    }
  };

  public name: string = '';
  public email: string = '';
  public password: string = '';

  constructor() {
    super();
  }

  public submit() {
    // i don't know if this form is valid or not :(
      console.log('in submit');
  }
}
</script>

1 个答案:

答案 0 :(得分:0)

我没有使用Typescript,但是最终,您必须在Submit上验证每个模型。因此,在您拥有的submit()函数中,执行preventDefault(),验证您的字段,如果一切正常,那么请继续将表单提交到后端。

请阅读常规工作流程指南:https://vuejs.org/v2/cookbook/form-validation.html

另外,请签出VuelidateVeeValidate,它们是针对VueJS的简单验证框架。

p.s .:请参阅:首先使用Vuelidate with Typescript发出良好的指针。