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.
Props and data are both reactiveWith Vue you don't need to think all that much about when the component will update itself and render new changes to the screen. This is because Vue is reactive. Instead of calling setState every time you want to change something, you just change the thing!
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.
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
}
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With