Reputation: 10312
I have a component that has two props, but in order to be valid only one of them should be provided.
Example:
// either `email` or `phone` should be passed (but not both)
props: {
email: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
}
Is there a way to validate props based on each other?
I'm thinking of putting this somewhere in a lifecycle hook, but it feels out of place.
Upvotes: 6
Views: 1798
Reputation: 73906
I think lifecycle hook would not be a good place to put the validation logic, as the hooks are called only once and thus if the prop values changes in future, then you will not get the same validations again. Instead, you can try to use set a watcher on the Vue instance's $props
object to watch for any changes to the props value in future and trigger validation on each change like:
props: {
email: String,
phone: String
},
methods: {
validateProps() {
// Here you can access both props and add your validation logic
if(!this.email && !this.phone){
console.error('Please add either email or phone props');
}
}
},
watch: {
$props: {
immediate: true,
handler() {
this.validateProps();
}
}
}
Here, I have added a basic validation logic, you can update it as per your requirements.
Upvotes: 9
Reputation: 1843
I would suggest using a computed property.
<template>
<div>{{ emailOrPhone }}</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
email: {
type: String
},
phone: {
type: String
}
},
computed: {
emailOrPhone() {
return this.email || this.phone || 'warning: email or phone required';
}
}
};
</script>
Upvotes: 1
Reputation: 5071
In created
hook of your component instance you can access this.$props
(it will be an array or object [in your case object], containing all props passed to this component). Then you can check is property existing in this object if not you can throw an error or show notification (whatever you want).
...
created() {
if(this.$props.email == null && this.$props.phone == null) {
throw Error('You have to pass at least one prop');
}
},
...
You also have to remember to remove this required: true
flag:
props: {
email: {
type: String
},
phone: {
type: String
}
},
Upvotes: 5