如何使用vuejs实现更好的Form validation
1个回答
展开全部
举个例子吧,我用的的是vue-form
html:
<form v-form name="myform" @submit.prevent="onSubmit" role="form">
<legend class="text-center">Vue-form demo</legend>
<div class="form-group">
<label>邮箱*</label>
<input class="form-control" v-model="model.name" v-form-ctrl required name="name" />
</div>
<div class="form-group">
<label>用户名*</label>
<input class="form-control" v-model="model.email" v-form-ctrl name="email" type="email" required />
</div>
<div class="errors" v-if="myform.$submitted">
<p class="bg-danger text-center" v-if="myform.name.$error.required">请输入用户名.</p>
<p class="bg-danger text-center" v-if="myform.email.$error.email">请输入正确的邮箱.</p>
</div>
<button class="btn btn-success btn-block" type="submit">提交</button>
</form>
js:
new Vue({
el: '#app',
data: {
myform: {},
model: {}
},
methods: {
onSubmit: function() {
console.log(this.myform.$valid);
if(this.myform.$valid==true)
alert("提交成功");
}
}
});
demo完整代码在这里可以查看
html:
<form v-form name="myform" @submit.prevent="onSubmit" role="form">
<legend class="text-center">Vue-form demo</legend>
<div class="form-group">
<label>邮箱*</label>
<input class="form-control" v-model="model.name" v-form-ctrl required name="name" />
</div>
<div class="form-group">
<label>用户名*</label>
<input class="form-control" v-model="model.email" v-form-ctrl name="email" type="email" required />
</div>
<div class="errors" v-if="myform.$submitted">
<p class="bg-danger text-center" v-if="myform.name.$error.required">请输入用户名.</p>
<p class="bg-danger text-center" v-if="myform.email.$error.email">请输入正确的邮箱.</p>
</div>
<button class="btn btn-success btn-block" type="submit">提交</button>
</form>
js:
new Vue({
el: '#app',
data: {
myform: {},
model: {}
},
methods: {
onSubmit: function() {
console.log(this.myform.$valid);
if(this.myform.$valid==true)
alert("提交成功");
}
}
});
demo完整代码在这里可以查看
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询