From b45d4172b69b288a743c49027934c89fb416d0d8 Mon Sep 17 00:00:00 2001 From: Toni Date: Fri, 24 May 2024 10:25:27 +0800 Subject: [PATCH] Added a validation for all Text Input --- src/components/Home.js | 56 +++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/src/components/Home.js b/src/components/Home.js index 465912e..5cdb3f3 100644 --- a/src/components/Home.js +++ b/src/components/Home.js @@ -1,4 +1,4 @@ -import {Button, TextInput, rem, PasswordInput} from '@mantine/core'; +import {Button, TextInput, rem, PasswordInput, Text} from '@mantine/core'; import { IconAt } from '@tabler/icons-react'; import {useState} from 'react'; import {http} from "../middleware/axiosConfig"; @@ -25,17 +25,38 @@ function Home() { // Initialize state to handle loading state const [loading,setLoading]=useState() + const [errors, setErrors] =useState({}) + + //Inserts new account to the Database{reactapp.users}.post const onSubmitChange = async (e) => { e.preventDefault(); - try{ - const response= await http.post("/api/addnew", userField); - console.log(response) - setLoading(true); - } catch(err){ - console.error(err) - console.log("Something's Wrong!"); + //validation for errors + const validationErrors = {} + if (!userField.name.trim()){ + validationErrors.name = Name is Required! } + if (!userField.email.trim()){ + validationErrors.email = Email is Required! + } else if(!/^\S+@\S+$/.test(userField.email)){ + validationErrors.email = Email is Invalid! + } + if (!userField.password.trim()){ + validationErrors.password = Password is Required! + } else if(userField.password.length < 6){ + validationErrors.password = Password should be at least 6 characters! + } + + try { + setErrors(validationErrors) + const response = await http.post('/api/addnew', userField); + console.log(response); + } catch (err) { + console.error(err); + console.log("Something's Wrong!"); + } finally { + setLoading(true); + } } //If loading is true, return to @@ -47,7 +68,7 @@ function Home() { return (

ADD ACCOUNT

-
+
{/* Name Input */}
@@ -58,11 +79,13 @@ function Home() { name='name' id='name' onChange={e => changeUserFieldHandler(e)} - style={{ width: '400px', marginBottom: '10px' }}/>
+ style={{ width: '400px', marginBottom: '10px' }}/> +
+ {/* Validation Error */} + {errors.name &&
{errors.name}
} {/* E-mail Input */}
changeUserFieldHandler(e)} style={{ width: '400px', marginBottom: '10px' }}/>
+ {/* Validation Error */} + {errors.email &&
{errors.email}
} {/* Password Input */}
changeUserFieldHandler(e)} style={{ width: '400px', marginBottom: '10px' }}/>
+ {/* Validation Error */} + {errors.password &&
{errors.password}
} {/* Submit Button - triggers the onSubmitChange function*/}
- +
@@ -94,4 +120,4 @@ function Home() { ); } -export default Home; +export default Home \ No newline at end of file