vue前端表单常用的邮箱、电话、身份证、url、Ip等正则式多语言版校验
在Vue中,你可以使用第三方库如vee-validate
来实现表单验证。以下是一个使用vee-validate
库进行邮箱、电话号码、身份证号码、URL和IP地址验证的示例:
首先,安装vee-validate
:
npm install vee-validate@3 --save
然后,在你的Vue组件中使用它:
<template>
<ValidationObserver ref="observer">
<form @submit.prevent="validateBeforeSubmit">
<ValidationProvider name="email" rules="required|email" v-slot="{ errors }">
<input type="text" v-model="email" placeholder="Email">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="phone" rules="required|phone" v-slot="{ errors }">
<input type="text" v-model="phone" placeholder="Phone">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="id" rules="required|id" v-slot="{ errors }">
<input type="text" v-model="id" placeholder="ID">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="url" rules="required|url" v-slot="{ errors }">
<input type="text" v-model="url" placeholder="URL">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="ip" rules="required|ip" v-slot="{ errors }">
<input type="text" v-model="ip" placeholder="IP">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<button>Submit</button>
</form>
</ValidationObserver>
</template>
<script>
import { extend, ValidationObserver, ValidationProvider, setInteractionMode } from 'vee-validate';
import { required, email, phone, is } from 'vee-validate/dist/rules';
setInteractionMode('eager');
extend('phone', phone);
extend('id', is({ pattern: '^\\d{17}[\\d|X]$' })); // 中国的居民身份证号码正则
extend('url', is({ pattern: '^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$' }));
extend('ip', is({ pattern: '^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$' }));
export default {
components: {
ValidationObserver,
ValidationProvider
},
data() {
return {
email: '',
phone: '',
id: '',
url: '',
ip: ''
};
},
methods: {
validateBeforeSubmit() {
this.$refs.observer.validate().then(isValid => {
if (isValid) {
// Handle form submission
}
});
}
}
};
</script>
在这个例子中,我们使用了\`vee
评论已关闭