From 01679fbd0133deed9c0c49ef299e6d4cf34a87e7 Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Wed, 6 Mar 2024 18:36:22 +0000 Subject: [PATCH] Add name validation to snippets --- .../common/bindings/SnippetDrawer.svelte | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte index f3a605bed4..d660f295c0 100644 --- a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte +++ b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte @@ -17,6 +17,7 @@ export const hide = () => drawer.hide() const roughValidNameRegex = /^[_$A-Z\xA0-\uFFFF][_$A-Z0-9\xA0-\uFFFF]*$/i + const firstCharNumberRegex = /^[0-9].*$/ let drawer let name = "" @@ -26,7 +27,7 @@ $: name = snippet?.name || "MySnippet" $: code = snippet?.code ? encodeJSBinding(snippet.code) : "" $: rawJS = decodeJSBinding(code) - $: nameValid = validateName(name) + $: nameError = validateName(name) const saveSnippet = async () => { await snippetStore.saveSnippet({ @@ -48,14 +49,20 @@ // try executing it and see if it's valid JS. The initial regex prevents // against any potential XSS attacks here. const validateName = name => { + if (!name?.length) { + return "Name is required" + } + if (firstCharNumberRegex.test(name)) { + return "Can't start with a number" + } if (!roughValidNameRegex.test(name)) { - return false + return "No special characters or spaces" } const js = `(function ${name}(){return true})()` try { - return eval(js) === true + return eval(js) === true ? null : "Invalid name" } catch (error) { - return false + return "Invalid name" } } @@ -65,14 +72,11 @@ {#if snippet} {snippet.name} {:else} -
+
Name - {#if !nameValid} - + {#if nameError} + Delete {/if} - @@ -117,9 +121,12 @@ align-items: center; position: relative; } - .name.invalid :global(input) { + .name :global(input) { width: 200px; } + .name.invalid :global(input) { + padding-right: 32px; + } .name :global(.icon) { position: absolute; right: 10px;