From 0870589dab3fa46f59a1d6b128528c570da74cc7 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Tue, 19 Jan 2021 14:14:38 +0200 Subject: Implement before-submit validation (broken, crashing) --- src/components/Question.tsx | 63 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) (limited to 'src/components/Question.tsx') diff --git a/src/components/Question.tsx b/src/components/Question.tsx index 81c43b2..df9d18e 100644 --- a/src/components/Question.tsx +++ b/src/components/Question.tsx @@ -19,6 +19,7 @@ const skip_normal_state: Array = [ export type QuestionProp = { question: Question, public_state: Map, + scroll_ref: React.RefObject } class RenderedQuestion extends React.Component { @@ -146,6 +147,66 @@ class RenderedQuestion extends React.Component { this.setPublicState("value", event.target.value); } + validateField(): void { + if (!this.props.question.required) { + return; + } + + let invalid = false; + const options: string | string[] = this.props.question.data["options"]; + switch (this.props.question.type) { + case QuestionType.TextArea: + if (this.props.public_state.get("value") === "") { + invalid = true; + } + break; + + case QuestionType.ShortText: + if (this.props.public_state.get("value") === "") { + invalid = true; + } + break; + + case QuestionType.Select: + if (!this.props.public_state.get("value")) { + invalid = true; + } + break; + + case QuestionType.Range: + if (!this.props.public_state.get("value")) { + invalid = true; + } + break; + + case QuestionType.Radio: + if (!this.props.public_state.get("value")) { + invalid = true; + } + break; + + case QuestionType.Checkbox: + if (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))) { + invalid = true; + } + } + break; + } + + if (invalid) { + this.setPublicState("error", "Field must be filled."); + this.setPublicState("valid", false); + } else { + this.setPublicState("error", ""); + this.setPublicState("valid", true); + } + } + componentDidMount(): void { // Initialize defaults for complex and nested fields const options: string | string[] = this.props.question.data["options"]; @@ -228,7 +289,7 @@ class RenderedQuestion extends React.Component { error = rawError; } - return
+ return

{question.name}*

-- cgit v1.2.3