Browse Source

added custom input validation library and validate method

liontix 10 months ago
parent
commit
79c7ca7d68
2 changed files with 32 additions and 1 deletions
  1. 3 1
      package.json
  2. 29 0
      src/lib/modules/AppointmentRegisterInputs.svelte

+ 3 - 1
package.json

@@ -17,6 +17,7 @@
 		"@sveltejs/adapter-auto": "^3.0.0",
 		"@sveltejs/kit": "^2.9.0",
 		"@sveltejs/vite-plugin-svelte": "^5.0.0",
+		"@types/validator": "^13.12.2",
 		"eslint": "^9.7.0",
 		"eslint-config-prettier": "^9.1.0",
 		"eslint-plugin-svelte": "^2.36.0",
@@ -31,6 +32,7 @@
 	},
 	"dependencies": {
 		"@sveltejs/adapter-vercel": "^5.5.2",
-		"beercss": "^3.8.0"
+		"beercss": "^3.8.0",
+		"validator": "^13.12.0"
 	}
 }

+ 29 - 0
src/lib/modules/AppointmentRegisterInputs.svelte

@@ -1,5 +1,6 @@
 <script lang="ts">
 	import type { AppointmentInputs } from "$lib/dbdata";
+    import validator from "validator";
 
     let dynamicInputs: AppointmentInputs[] = [
         {name: "First name", type: "text"},
@@ -8,12 +9,36 @@
     ];
 
     let inputValues: Record<string, string> = {};
+    let errorMessage: string = "";
+
+    function validateInput(value: string, type: string): boolean  {
+        switch (type) {
+            case "email":
+                return validator.isEmail(value);
+        
+            case "text":
+                return !validator.isEmpty(value);
+
+            case "tel":
+                return validator.isMobilePhone(value);
+
+            default:
+                return false;
+        }
+    }
 
     function submit() {
         const jsonOutput: Record<string, any> = {};
+        errorMessage = "";
+        if (Object.keys(inputValues).length != dynamicInputs.length) {
+            errorMessage = "Not all inputs filled";
+        }
         for (const dInput of dynamicInputs) {
             if (inputValues[dInput.name]) {
                 jsonOutput[dInput.name] = inputValues[dInput.name];
+                if (!validateInput(jsonOutput[dInput.name], dInput.type)) {
+                    errorMessage = "Invalid inputs";
+                }
             }
         }
         console.log(jsonOutput); // Output the JSON object
@@ -28,4 +53,8 @@
     </div>
 {/each}
 
+{#if errorMessage}
+    <p class="error-text">{errorMessage}</p>
+{/if}
+
 <button on:click={submit}>Submit</button>