From cf8e125c867ff01852a03a6eb107be2e2cc96c8f Mon Sep 17 00:00:00 2001
From: ks129 <45097959+ks129@users.noreply.github.com>
Date: Tue, 19 Jan 2021 08:12:16 +0200
Subject: Implement validation for checkboxes

---
 src/components/Question.tsx | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

(limited to 'src/components/Question.tsx')

diff --git a/src/components/Question.tsx b/src/components/Question.tsx
index 12cde5d..81c43b2 100644
--- a/src/components/Question.tsx
+++ b/src/components/Question.tsx
@@ -113,10 +113,28 @@ class RenderedQuestion extends React.Component<QuestionProp> {
             event.target.parentElement.classList.toggle("selected");
         }
 
+        const options: string | string[] = this.props.question.data["options"];
         switch (event.target.type) {
             case "text":
                 this.setPublicState("valid", true);
                 break;
+            
+            case "checkbox":
+                // We need to check this here, because checkbox doesn't have onBlur
+                if (this.props.question.required && typeof options !== "string") {
+                    const keys: string[] = [];
+                    options.forEach((val, index) => {
+                        keys.push(`${("000" + index).slice(-4)}. ${val}`);
+                    });
+                    if (keys.every(v => !this.props.public_state.get(v))) {
+                        this.setPublicState("error", "Field must be filled.");
+                        this.setPublicState("valid", false);
+                    } else {
+                        this.setPublicState("error", "");
+                        this.setPublicState("valid", true);
+                    }
+                }
+                break;
         }
     }
 
-- 
cgit v1.2.3

