我正在尝试使用Vuetify.js示例在使用Vue.js构建的网站上添加简单验证的联系表单。我是新手,所以我不确定它应该如何在Vue组件中实现。
我希望实现一个简单的客户端表单验证,并使其与https://getform.org/表单一起使用。
更新:
(取自Vuetify.js表格example)
<v-form v-model="valid">
<v-text-field
label="Name"
v-model="name"
:rules="nameRules"
:counter="10"
required
name="Name"
></v-text-field>
<v-text-field
label="E-mail"
v-model="email"
:rules="emailRules"
required
name="Email"
></v-text-field>
<v-btn
@click="submit"
:disabled="!valid"
>submit</v-btn>
</v-form>
<form method="post" action="https://www.getform.org/f/[MY_ID_HERE]" id="nativeForm"></form>
<script>
export default {
name: 'contact',
data () {
return {
snackbar: true,
valid: false,
name: '',
nameRules: [
(v) => !!v || 'Name is required',
(v) => v.length <= 10 || 'Name must be less than 10 characters'
],
email: '',
emailRules: [
(v) => !!v || 'E-mail is required',
(v) => /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
]
}
},
methods: {
submit() {
nativeForm.submit()
}
}
}
</script>
答案 0 :(得分:8)
<v-form method="post" action="https://www.getform.org/f/[YOUR-FORM-ID]" id="nativeForm" v-model="valid">
<v-text-field
label="Name"
v-model="name"
:rules="nameRules"
:counter="10"
required
name="message"
></v-text-field>
<v-text-field
label="E-mail"
v-model="email"
:rules="emailRules"
required
name="mail"
></v-text-field>
<v-btn @click="submit" :disabled="!valid">submit</v-btn>
</v-form>
<script>
export default {
name: 'contact',
data () {
return {
valid: false,
name: '',
nameRules: [
(v) => !!v || 'Name is required',
(v) => v.length <= 10 || 'Name must be less than 10 characters'
],
email: '',
emailRules: [
(v) => !!v || 'E-mail is required',
(v) => /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
]
}
},
methods: {
submit() {
nativeForm.submit()
}
}
}
</script>
添加name
个属性。 Getform需要它们。
答案 1 :(得分:5)
const app = new Vue({
el:'#app',
data:{
errors:[],
name:null,
age:null,
movie:null
},
methods:{
checkForm:function(e) {
if(this.name && this.age) return true;
this.errors = [];
if(!this.name) this.errors.push("Name required.");
if(!this.age) this.errors.push("Age required.");
e.preventDefault();
}
}
})
input,select {
margin-left: 10px;
}
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<form id="app" @submit="checkForm" action="/something" method="post">
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
<p>
<label for="name">Name<label>
<input type="text" name="name" id="name" v-model="name">
</p>
<p>
<label for="age">Age<label>
<input type="number" name="age" id="age" v-model="age" min="0">
</p>
<p>
<label for="movie">Favorite Movie<label>
<select name="movie" id="movie" v-model="movie">
<option>Star Wars</option>
<option>Vanilla Sky</option>
<option>Atomic Blonde</option>
</select>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
添加一些CSS并完成。