Vue中常用的rules校验规则
warning:
这篇文章距离上次修改已过181天,其中的内容可能已经有所变动。
在Vue中,常用的表单验证规则可以通过第三方库如vee-validate
或Vue自带的v-model
结合computed properties
实现。以下是一些常见的验证规则示例:
- 必填项(required):
required: value => !!value || 'This field is required.'
- 最小长度(minLength):
minLength: min => value => value.length >= min || `The minimum length is ${min} characters.`
- 最大长度(maxLength):
maxLength: max => value => value.length <= max || `The maximum length is ${max} characters.`
- 邮箱(email):
email: value => /.+@.+\..+/.test(value) || 'This must be a valid email address.'
- 数字(number):
number: value => /^\d+$/.test(value) || 'This field must be a number.'
- 最小值(minValue):
minValue: min => value => value >= min || `The value must be greater than or equal to ${min}.`
- 最大值(maxValue):
maxValue: max => value => value <= max || `The value must be less than or equal to ${max}.`
在Vue组件中使用这些规则,可以这样定义data
:
data() {
return {
form: {
name: '',
email: ''
},
rules: {
name: [
{ validator: this.rules.required, message: 'Name is required.' }
],
email: [
{ validator: this.rules.required, message: 'Email is required.' },
{ validator: this.rules.email, message: 'Email must be valid.' }
]
}
};
}
在模板中使用v-model
和v-validate
指令:
<input v-model="form.name" v-validate="rules.name">
<span v-if="errors.has('name')">{{ errors.first('name') }}</span>
<input v-model="form.email" v-validate="rules.email">
<span v-if="errors.has('email')">{{ errors.first('email') }}</span>
这里errors.has('field')
检查字段是否有验证错误,errors.first('field')
显示第一条错误信息。如果使用vee-validate
,则可以更简洁地定义规则并使用内置的验证指令。
评论已关闭