What is the correct way to validate properties ? #3715
-
I'm creating my first Custom Component and everything works great except that now I have to validate the properties/attributes added to it. For example having this code (it's an example in real life I have like 10 html attributes for the component) :
If I always want to have
My aim is to be able to have some logic to validate these properties and changes them to a default value as a fallback that is reflected on the attribute. From this example it would be to delete the 'baz' value from If you have real life examples or advices it would be great ! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Custom converters only apply if users are providing the properties as attributes as that's when a converter would be called. If users are providing them as properties, you have a couple of options:
|
Beta Was this translation helpful? Give feedback.
-
Thanks for your answer I didn't think of the difference between setting the values as attributes vs properties... My "problem" if using willUpdate is that it implies repeating the same code multiple times to do the same action on multiple properties. As I said I must ensure that 5 properties are always positive integer, and wrintting something like this looks a little verbose :
I read the doc on computed properties (https://lit.dev/articles/lit-for-polymer-users/#computed-properties-and-observers) and as you said I should place the code inside the willUpdate method, but do you have any suggestion to optimize this checks ? |
Beta Was this translation helpful? Give feedback.
Custom converters only apply if users are providing the properties as attributes as that's when a converter would be called. If users are providing them as properties, you have a couple of options:
Use
willUpdate()
lifecycle to read the value and make any necessary changes before update/rendering. https://lit.dev/docs/components/lifecycle/#willupdateCreate custom property accessors (getters and setters) and do the validation on the setter. https://lit.dev/docs/components/properties/#accessors-custom