Correct way to validate attribute #266
Replies: 5 comments
-
For the required label attribute, I currently have this Is there an better alternative or would it need an implementation on minze itself? |
Beta Was this translation helpful? Give feedback.
-
There isn't a native attribute-checking functionality but you could use the following code. I used the util functions in a project. The Component file import { type Attrs, MinzeElement } from 'minze'
import { verifyAttrs } from './utils'
export interface MyElement {
type: 'text' | 'email'
label: string
}
export class MyElement extends MinzeElement {
attrs: Attrs = ['type', 'label']
static observedAttributes = ['type', 'label']
onStart = () => verifyAttrs(this, ['type', 'label'])
run = () => {
// exit early if attrs are missing
if (verifyAttrs(this, ['type', 'label'])) return
// your logic here
}
html = () => `<button on:click="run"></button>`
} Utils file import type { MinzeElement } from 'minze'
/**
* Converts a dash-case string to camelCase.
*
* @param value - The string to convert.
*
* @example
* dashToCamelCase('some-string') // 'someString'
*/
export function dashToCamel(value: string) {
return value.replace(/-([a-z])/g, (g) => g[1].toUpperCase())
}
/**
* Verifies that all required attributes are provided.
*
* @param component - A MinzeElement component class.
* @param attrs - An array of attributes.
*
* @example
* const hasMissingAttrs = verifyAttrs(this, ['type', 'label'])
*/
export function verifyAttrs(component: MinzeElement, attrs: string[]) {
const missingAttrs: string[] = []
attrs.forEach((attr) => {
const prop = dashToCamel(attr)
if (!component[prop]) missingAttrs.push(attr)
})
const hasMissingAttrs = !!missingAttrs.length
if (hasMissingAttrs) {
console.warn(`Missing required attributes: ${missingAttrs.join(', ')}`)
}
return hasMissingAttrs
} |
Beta Was this translation helpful? Give feedback.
-
Thank you. I find it kinda weird that nobody asked for this yet. |
Beta Was this translation helpful? Give feedback.
-
Just another question: how can / should I handle errors? Specifically an error that should not allow the element to render at all? |
Beta Was this translation helpful? Give feedback.
-
Ok, got it :D I think. |
Beta Was this translation helpful? Give feedback.
-
Hey there,
I have the following element:
<my-input type="text" label="Label" value="text"></my-input>
The attribute type is
type: "text" | "email"
How can I make sure, that type is type?
And how can I make sure, that label is always required?
Beta Was this translation helpful? Give feedback.
All reactions