Proposal for withValidation
: Advanced Prop Validation in Vue 3
#648
onmax
started this conversation in
RFC Discussions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
This RFC introduces
withValidation
, a feature that aims to enhance Vue 3's prop validation mechanism. It allows for collective prop validation, allowing developers to apply complex validation rules that consider multiple props simultaneously. This method improves the existing validation capabilities by providing a more expressive and readable syntax, facilitating early validation, and better supporting component libraries.Basic example
This code snippet illustrates how
withValidation
can be used to ensure that the type of thedefaultValue
prop matches the specified type prop, increasing the clarity and effectiveness of prop validation.For a real-world and more complex example, see this PR.
Motivation
Detailed design
The
withValidation
function wraps around the prop definition and allows developers to define a second argument - a validation function. This function evaluates the props based on the provided rules and returns either true for a pass or a string error message for a fail. This design supports a wide range of validation scenarios, from simple type checks to complex dependencies between props.This approach integrates seamlessly into the Vue component definition process, offering an elegant solution to include advanced validation logic.
Drawbacks
withValidation
in conjunction withwithDefaults
could lead to verbose code, especially in complex components.withValidation
adds complexity to the Vue core, potentially increasing the learning curve for new developers.validator
function: Unlike the Validator function, which returns aboolean
,withValidation
returnstrue | string
, encouraging developers to write an error messages in their componentsAlternatives
onBeforeMount
andonBeforeUpdate
hooks to validate props and handle the error:Expand to see code
Rely on generics. Since Vue 3.3, we can use generics like
<script setup lang="ts" generic="...">
. This is a great solution it does not apply in runtime. JS users cannot take advantage of this.Another approach is to continue to rely on external validation libraries, keeping the component and validation logic separate.
Adoption strategy
withValidation
is accompanied by extensive documentation, including examples covering a range of validation scenarios. The feature is designed to be backward compatible, allowing developers to adopt it at their own pace without the need for immediate refactoring of existing components.Unresolved questions
withValidation
in complex component ecosystemsvalidator
within thedefineProp
for the streamlined withValidation, simplifying Vue's validation approach.defineEmit
,withValidation
could be also used fordefineEmit
, but this should be part of another RFC.Beta Was this translation helpful? Give feedback.
All reactions