[英]How to validate form in Vue?
我想在 Vue 中構建注冊表單。
我認為我按照書本做的一切都很好。 但我的問題是,如果我使用Vuetify
和vue-property-decorator
v-form
,如何觸發驗證。
因為他們所有的例子都有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>
我沒有使用 Typescript,但最終,您必須在提交時驗證每個模型。 因此,在您擁有的submit()
函數中,執行preventDefault()
,驗證您的字段,如果一切正常,則繼續實際將表單提交到后端。
請閱讀一般工作流程指南: https ://v2.vuejs.org/v2/cookbook/form-validation.html
另外,請查看Vuelidate和VeeValidate ,它們是 VueJS 的簡單驗證框架。
ps:請參閱:首先將Vuelidate 與 Typescript問題一起使用以獲得良好的指示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.