VeeValidate 中文文档-Examples

1,166 阅读1分钟

本篇总结 Examples

源代码,在 Sandbox 查看:https://codesandbox.io/s/y3504yr0l1?initialpath=%2F%23%2Fform&module=%2Fsrc%2Fcomponents%2FForm.vue

个别写了一些例子的一部分,还是需要看官方代码!

验证表单: 我们可能希望在提交表单之前触发所有的 inputs 输入框验证,如果检测到任何错误,可能展示一个 alert 弹窗或阻止表单提交。使用验证器的 validate() 方法可以轻松实现这一点。

<template>
	<form @submit.prevent="validateBeforeSubmit">
        <div class="column is-12">
            <label class="label">Email</label>
            <p class="control has-icon has-icon-right">
                <input name="email" v-model="email" v-validate="'required|email'" :class="{'input': true, 'is-danger': errors.has('email') }" type="text" placeholder="Email">
                <i v-show="errors.has('email')" class="fa fa-warning"></i>
                <span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span>
            </p>
        </div>
	</form>
</template>
<script>
	export default {
		name: '表单示例',
		data: () => {
			email: '',
		},
		methods: {
			validateBeforeSubmit() {

				/*
					1.怎么出来的 this.$validator? 
						$validator 默认会自动注入到每个组件中
						inject 选项:
							inject - boolean - true - 指定是否应为所有组件自动注入验证器实例
					2.调用的是 validateAll() 方法,对表单所有字段进行验证
				 */ 
				this.$validator.validateAll().then((response) => {

				});
			}	
		}
	}
</script>

去抖(延迟)验证: 我们可以指定一个延迟,对 input 事件进行去抖动,一个常见的场景是,我们可能希望等待用户停止键入,然后再验证字段,以限制验证触发频率。(不需要用户每按下键盘一次,我们就触发验证,稍有个延迟)

这可以通过,在要验证的字段上添加 data-vv-delay 属性来实现,并为该属性指定我们想要等待的毫秒数。

<template>
    <div class="column is-12">
        <label class="label">Email (1s delay)</label>
        <p class="control has-icon has-icon-right">

        	// 这里使用了 data-vv-delay="1000",延迟 1000ms
            <input name="email" v-validate="'required|email'" data-vv-delay="1000" :class="{'input': true, 'is-danger': errors.has('email') }" type="text" placeholder="Email">
            <i v-show="errors.has('email')" class="fa fa-warning"></i>
            <span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span>
        </p>
    </div>
</template>
<script>
	export default {
		name: '延迟示例'
	}
</script>

验证模型: v-validate 指令检查,input 输入框是否具有绑定到同一输入的 v-model,监听该值,并在改变时验证它。默认是 input 事件触发。如果 .lazy 修饰符应用于该模型,将通过 change 事件来验证,而不遵从 v-model 指令。

<template>
    <div class="column is-12">
        <label class="label">Password</label>
        <p class="control has-icon has-icon-right">

        	// 这里给  v-model 使用了 'v-model.lazy' 修饰符
            <input name="passsword" v-model.lazy="passsword" v-validate="'required|alpha'" :class="{'input': true, 'is-danger': errors.has('passsword') }" type="text" placeholder="Password">
            <i v-show="errors.has('first_name')" class="fa fa-warning"></i>
            <span v-show="errors.has('first_name')" class="help is-danger">{{ errors.first('first_name') }}</span>
        </p>
    </div>
</template>
<script>
	export default {
		name: '模型示例',
		data: () => ({
			password: ''
		});
	}
</script>

验证初始值 如果我们正在使用服务端渲染,并且希望在渲染阶段填充 inputs 输入框的值,例如,当编辑记录时,我们可以在 v-validate 指令上,使用 immediate 修饰符来立即验证该字段。

<template>
    <div class="column is-12">
        <label class="label">First Name</label>
        <p class="control has-icon has-icon-right">

        	// 这里使用了 'v-validate.initial' 修饰符
        	// 加载页面后,立即进行验证。发现 first_name 为空,会立即显示验证错误
            <input name="first_name" v-model="first_name" v-validate.initial="'required|alpha'" :class="{'input': true, 'is-danger': errors.has('first_name') }" type="text" placeholder="First Name">
            <i v-show="errors.has('first_name')" class="fa fa-warning"></i>
            <span v-show="errors.has('first_name')" class="help is-danger">{{ errors.first('first_name') }}</span>
        </p>
    </div>
</template>
<script>
	export default {
		name: '初始值示例',
		data: () => ({
			first_name: ''
		});
	}
</script>

输入锁定和 :value 绑定
	警告:
		我们可能会尝试使用 :value 绑定来填充我们字段的初始值,但是这会导致 inputs 输入框被 "锁定",似乎不接收用户的输入。发生这种情况是因为,Vue 2.0 开始,组件模板就像一个函数,只要组件更新它就会运行,从而导致了 input 输入框恢复到过去绑定的值。

		要解决此问题,我们可以使用 refs 来填充值。我们可以从这里获取更多信息(https://github.com/vuejs/vue/issues/3924)。

验证 Vuex State 验证 vuex state 可能很棘手,因为为了改变 state,我们必须触发 mutation。如下所示:

	<input type="text" @input="updateMessage" v-validate="'required'">

	computed: {
	  	...mapState({
	    	message: state => state.obj.message
	  	})
	},
	methods: {
	  	updateMessage (e) {
	    	this.$store.commit('updateMessage', e.target.value)
	  	}
	}

但是这对 input 事件不起作用。这是因为验证器的处理程序和 updateMessage 方法不同步。为了解决这个问题,我们需要为 Vuex state 开启双向绑定,使用计算属性的 setters,很容易实现,并允许我们在 inputs 输入框上使用 v-model。

我们的代码如下:
	<input name="message" v-model="message" v-validate="'required|min:5'" type="text" placeholder="Your Message">

	computed: {
	  	message: {
	    	get () {
	     	 	return this.$store.state.message;
	    	},
	    	set (val) {
	    		this.$store.commit('UPDATE_MESSAGE', val);
	    	}
	  	}
	}

验证单选按钮 vee-validate 也支持验证单选按钮。我们可以在单选按钮上使用任何我们想要的规则,但只有少数规则有意义,如 required。在本例中要注意的一件事是,我们只需要在其中一个单选按钮上使用指令,不需要在每个按钮上附加指令。它们都必须拥有相同的 name 名称。

<template>
    <div class="column is-6">
        <legend :class="{ 'error': errors.has('radio_group_1') }">Radio Group 1</legend>
        <p class="control">
            <label class="radio">

            	// 只有这个单选按钮,使用了 'v-validate' 指令
                <input name="radio_group_1" v-validate="'required|included:1,2'" value="1" type="radio">
                Option 1
            </label>
            <label class="radio">
                <input name="radio_group_1" value="2" type="radio">
                Option 2
            </label>
            <label class="radio">
                <input name="radio_group_1" value="3" type="radio">
                Option 3
            </label>
        </p>
        <span class="help is-danger" v-show="errors.has('radio_group_1')">{{ errors.first('radio_group_1') }}</span>
    </div>
</template>
<script>
	export default {
		name: '单选按钮示例',
		data: () => ({
			first_name: ''
		});
	}
</script>

验证复选框 vee-validate 也支持验证复选框。然而,与单选按钮一样,支持的范围受 input 输入框自身的限制,但所有规则都适用。与单选按钮一样,我们只需在要验证的复选框上,附加验证器指令和属性。如果有多个复选框(组),我们只需在其中一个复选框上添加指令。

如果选择了多个值,验证器将在每个复选框上应用验证。

在下面的例子中,复选框验证的最基本用法是,用户勾选的阅读条款和条件协议。

<template>
    <div>
        <p class="control">
            <label class="checkbox">
                <input name="terms" v-validate="'required'" type="checkbox">
                I agree to the terms and conditions.
            </label>
            <span class="help is-danger" v-show="errors.has('terms')">{{ errors.first('terms') }}</span>
        </p>
    </div>
	<p class="control">
        <button type="button" class="button is-primary" @click="nextStep">Next</button>
	</p>
</template>
<script>
	export default {
		name: '复选框示例',
		methods: {
			nextStep() {
				this.$validator.validateAll().then((result) => {

				});
			}
		}
	}
</script>

异步后端验证 假设我们要验证特定于我们应用域名的某些内容,这在客户端是不可行的。例如,检查 email 是否已注册。

作用域 默认情况下,验证器的作用域同拥有它的 Vue 实例的作用域相同。有时我们可能在同样的组件内,有多个字段,这些字段具有不同的形式并用于不同的目的。由于验证器使用 name 和 data-vv-name 属性来识别字段,因此具有相同名称的字段,将相互冲突,这会在尝试显示它们中任意一个的错误消息时,导致问题。

我们可以通过添加 data-vv-scope 属性,告诉验证器对字段分配作用域。之后可以通过其名称和作用域来识别这些字段。我们可以在不同的作用域内使用同样名称的 inputs 输入框,并且我们可以独立地显示、清除和验证这些作用域。

为方便起见,我们可以在 inputs 输入框所属的 form 上添加 data-vv-scope 属性,我们不必为每个 input 添加该属性。我们还可以将 scope 属性传递给验证器表达式。

提示:
	应用在 form 上的 data-vv-scope,就如同 data-vv-scope 应用在这些 inputs 输入框上。自定义组件需要使用 data-vv-scope 来定义它们的作用域。

错误选择器 errors.first 和 errors.has 方法不仅给我们提供了获取指定字段的第一个输入的方法,还允许我们使用 'field:rule' 语法,进一步将其过滤到指定规则。甚至,它们允许我们使用 'scope.field' 将其过滤到指定作用域,因此,如果我们想要显示,newsletter 表单中 email 字段的第一个错误,但仅当规则是 emial 时,可以如下使用:

	errors.first('newsletter.email:email');

在下面的示例中,我们有一个错误的集合,并且我们可以使用 input 来过滤这些错误。注意,默认情况下,同一个 input 输入框的错误包,不会有多个错误,因为验证器设置的 bail,会在第一个规则失败时停止验证。

自定义组件验证 我们可能有一个 '想要作为 input 的' 自定义组件。像自定义 input 字段一样,它会有自己的验证器实例,但是我们想在父级作用域验证它,因为它只是顶层的(on top)一个带有一些 whistles 的输入。我们可以像使用常规 input 元素一样,使用指令来实现此目的,但我们必须确保我们的组件满足一下条件: 1>每当值发生变化,必须 emit 一个 input 事件 2>应该在组件的 $_veeValidate ctor 选项中定义一个 value 和 name getters,或者可以使用 data-vv-name 和 data-vv-value-path 来替代。

<template>
  	<div>
    	<text-input name="email" v-validate="'required|email'"></text-input>
    	{{ errors.first('email') }}
  	</div>
</template>

<script>
	import TextInput from './TextInput';

	export default {
	  	components: {
	    	TextInput
	  	} 
	}
</script>

TextInput 组件:
	<template>
		<input type="text" :name="name" @input="$emit('input', $event.target.value)">
	</template>
	<script>
		export default {
		  	name: 'text-input',
		  	$_veeValidate: {
			    // value getter
			    value () {
			      	return this.$el.value;
			    },
			    // name getter
			    name () {
			      	return this.name;
			    }
		  	},
		  	props: {
			    name: String,
			    value: {
			      	type: null,
			      	default: null
			    }
		  	},
		  	mounted () {
		    	this.$el.value = this.value;
		  	}
		}
	</script>

本地化消息 我们可能想要以不同的语言来显示错误消息。vee-validate 提供了灵活的多语言支持。

下面是两个示例:

1.简单的本地化:


2.使用异步加载语言文件,进行本地化:

Validation Providers - 之前讲过的组件 这个例子使用了 v2.1 版本引入的 VeeValidate 组件来验证 Vuetify 的 输入。