vue系列:vue中使用vee-validate3表单验证
vee-validate 可以说是 vue 里表单验证 star 最高的了,今天来实践一下具体怎么用。代码npm install vee-validate --save我安装下来是 3.3.0 版本<ValidationObserver ref="form"><ValidationProvider rules="required" name="姓名" v-slot="{ erro
·
vee-validate 可以说是 vue 里表单验证 star 最高的了,今天来实践一下具体怎么用。
dom代码
npm install vee-validate --save
我安装下来是 3.3.0 版本
<ValidationObserver ref="form">
<ValidationProvider rules="required" name="姓名" v-slot="{ errors }">
<div class="form-part username">
<label for="">姓名</label>
<input type="text"
class="form-input"
maxlength="20"
v-model="formData.username"
placeholder="请输入姓名">
</div>
<span class="vee-error">{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider rules="required|isPhone" name="手机号" v-slot="{ errors }">
<div class="form-part phone">
<label for="">手机号</label>
<input type="text"
class="form-input"
v-model="formData.phone"
placeholder="请填写手机号">
</div>
<span class="vee-error">{{ errors[0] }}</span>
</ValidationProvider>
</ValidationObserver>
vuets 代码,vuejs同理
<script lang="ts">
// 让vue可以用ts
import { Vue, Component } from 'vue-property-decorator'
// 引入vee-validate
import { ValidationProvider, ValidationObserver, extend, localize } from 'vee-validate'
// 引入验证规则,可以自定义,如下的isPhone
import { required } from 'vee-validate/dist/rules'
// 汉化
import zhCN from 'vee-validate/dist/locale/zh_CN.json'
interface FormDataInter {
username: string;
province: string;
city: string;
hospital: string;
phone: string;
}
// 汉化
localize('zh_CN', zhCN)
// 引入验证规则
extend('required', required)
// 自定义验证规则
extend('isPhone', {
validate: value => {
const isPhone: boolean = /^[1][0-9]{10}$/.test(value)
return isPhone
},
message: '手机号格式不正确'
})
// 引入验证组件
@Component({
components: {
ValidationProvider,
ValidationObserver
}
})
export default class extends Vue {
private formData: FormDataInter = {
username: '',
province: '',
city: '',
hospital: '',
phone: ''
}
// 点击提交按钮触发
private submit (): void {
// 提交时候出发验证
// eslint-disable-next-line
(this.$refs.form as any).validate().then((success: boolean) => {
if (success) {
console.log(this.formData)
}
})
}
}
</script>
更多推荐
已为社区贡献18条内容
所有评论(0)