下面是我的代码。我已经在 addEmployee.vue 文件中完成了验证,并将验证写入了 addEmploee.vue 文件的脚本部分。但我想将这些验证放在 common.js 文件中,并且也想访问其他 vue 文件中的验证(在整个项目中),例如:我也想在 addClient.vue 文件中访问相同的验证。
<template>
<b-card>
<h4 slot="header" class="card-title">Employee</h4>
<b-row>
<b-col sm="3">
<b-form-group>
<label for="name">First Name </label>
<input type="text" id="" class="form-control" placeholder="Enter your name" v-validate="'required|Name'" name="Firstname">
<span v-show="errors.has('Firstname')" class="is-danger">{{ errors.first('Firstname') }}</span>
</b-form-group>
</b-col>
<b-col sm="3">
<b-form-group>
<label for="name">Middle Name </label>
<b-form-input type="text" id="" placeholder="Enter your name"></b-form-input>
</b-form-group>
</b-col>
<b-col sm="3">
<b-form-group>
<label for="name">Last Name </label>
<input type="text" id="" class="form-control" placeholder="Enter your middle name" v-validate="'required|Name'" name="Lastname">
<span v-show="errors.has('Lastname')" class="help is-danger">{{ errors.first('Lastname') }}</span>
</b-form-group>
</b-col>
</b-row>
<b-row>
<b-col sm="3">
<b-form-group>
<label for="name">D.O.B</label>
<input type="text" id="" class="form-control" placeholder="Date of birth" v-validate="'required|Number'" name="dob">
<span v-show="errors.has('dob')" class="help is-danger">{{ errors.first('dob') }}</span>
</b-form-group>
</b-col>
<b-col sm="3">
<b-form-group>
<label for="name">Contact</label>
<input type="text" id="" class="form-control" placeholder="Contact number" v-validate="'required|Number'" name="phNo#">
<span v-show="errors.has('phNo#')" class="help is-danger">{{ errors.first('phNo#') }}</span>
</b-form-group>
</b-col>
<b-col sm="3">
<b-form-group>
<label for="name">Email</label>
<b-form-input type="text" id="name" placeholder="Email-Id"></b-form-input>
</b-form-group>
</b-col>
</b-row>
<input type="submit" value="Submit" @click="validateForm">
</b-card>
</template>
<script>
export default {
name: 'addEmpl',
created: function() {
this.$validator.extend('Name', {
getMessage: field => '* Enter valid ' + field + '',
validate: value => /^[a-zA-Z]*$/.test(value)
});
this.$validator.extend('Number', {
getMessage: field => '* Enter valid ' + field + '',
validate: value => /^[0-9]{10}$/.test(value)
});
},
methods: {
validateForm() {
this.$validator.validateAll().then((result) => {
if(!result){
alert('not submitted')
return
}
alert('submitted')
}).catch(() => {
// error check if needed
});
}
}
}
</script>
<style lang="scss" scoped>
.is-danger{
color: RED;
}
</style>