How to Validate Minimum Age Greater & Equal to 18 Reactjs - reactjs

For the SignUp page I need to validate age is equal to or greater than 18. I have attempted using similar examples but all require me to install a dependency. I am looking for a way to achieve the desired results through React. My code is as follows
signup.jsx
import React from "react";
import { useState, useRef } from "react";
import { BsFillInfoCircleFill } from "react-icons/bs";
import Tooltip from "react-bootstrap/Tooltip";
import OverlayTrigger from "react-bootstrap/OverlayTrigger";
import { Link } from "react-router-dom";
import Alert from 'react-bootstrap/Alert'
import { UserAuth } from "../../AuthContext";
const Password = (props) =>
{
const [passwordShown, setPasswordShown] = useState(false);
const togglePassword = () => {
setPasswordShown(!passwordShown);
}
return(
<div className="input-group w-75 mb-5">
<input
type= {passwordShown ? 'text' : 'password'}
ref = {props.myRef}
className="form-control shadow-none"
placeholder="PSU1>OSU!"
aria-describedby="button-addon2"
></input>
<button onClick={togglePassword}>Show Password</button>
</div>
);
}
const SignUpPopup = (props) => {
//input fields
const firstName = useRef("");
const lastName = useRef("");
const email = useRef("");
const DOB = useRef("");
const password = useRef("");
const passwordConfirm = useRef("");
const [checked1, setChecked1] = useState(false);
const [checked2, setChecked2] = useState(false);
var errorMessage = ""
//change handlers
const handleChange1 = () => { setChecked1(!checked1) } ;
const handleChange2 = () => { setChecked2(!checked2) } ;
const [error, setError] = useState("");
const {createUser} = UserAuth();
//IMPROVE THE CHECKING OF THE FORM
function checkSignUp(){
var success = true
if (firstName.current.value === ""){
success = false
errorMessage += "Invalid first name\n"
}
if (lastName.current.value === ""){
success = false
errorMessage += "Invalid last name\n"
}
if (email.current.value === ""){
success = false
errorMessage += "Invalid email\n"
}
if (password.current.value === "" ){
success = false
errorMessage += "Invalid password\n"
}
if (!(passwordConfirm.current.value === password.current.value ) ){
success = false
errorMessage += "Passwords do not match\n"
}
return success;
}
async function addUserToDatabase(uid){
fetch("URL",{
method: "POST",
headers: { "Content-Type": "application/json"},
body: uid
})
}
async function handleSignup() {
setError("")
//if res == true, success, else failure and trigger alert
var res = checkSignUp();
if(res){
//authenticate
try{
await createUser(email.current.value, password.current.value);
const {user} = UserAuth();
addUserToDatabase(user.uid);
props.handleClose();
props.signupNextFunc();
}
catch(e){
errorMessage += "Invalid email or password"
setError(errorMessage)
}
}
}
const changeToLogin = ()=>{
props.handleClose()
props.loginFunc()
}
return (
<div className="popup-box">
<div className="box">
<div className="upperwrapper">
<span className="close-icon" onClick={props.handleClose}>
x
<input
type="text"
ref={firstName}
className="form-control shadow-none"
placeholder="Ben"
aria-describedby="button-addon2"
></input>
</div>
{/* LAST NAME INPUT */}
<p style={{ fontSize: "20px", marginTop: "15px" }}>
Last Name<span className="required-field"></span>
</p>
<div className="input-group w-75 mb-5">
<input
type="text"
ref = {lastName}
className="form-control shadow-none"
placeholder="Dover"
aria-describedby="button-addon2"
></input>
</div>
{/* EMAIL INPUT */}
<p style={{ fontSize: "20px", marginTop: "45px" }}>
Email<span className="required-field"></span>
</p>
<div className="input-group w-75 mb-5">
<input
type="text"
ref = {email}
className="form-control shadow-none"
placeholder="bendover#email.com"
aria-describedby="button-addon2"
></input>
</div>
<div className="d-flex bd-highlight mb-3 example-parent">
<p style={{ fontSize: "20px", marginTop: "10px" }}>
Date of Birth<span className="required-field"></span>
</p>
<div style={{ display: 'block', marginLeft: "-3px", marginTop: "-8px" }}
className="align-self-center p-2 bd-highlight col-example">
<OverlayTrigger
delay={{ hide: 450, show: 300 }}
overlay={(props) => (
<Tooltip {...props}>
Please provide your date of birth to validate...
</Tooltip>
)}
placement="right"
>
<div><BsFillInfoCircleFill /></div>
</OverlayTrigger>
</div>
</div>
<div className="input-group w-75 mb-5">
<input
type="date"
ref={DOB}
className="form-control shadow-none"
placeholder="mm/dd/yyyy"
aria-describedby="button-addon2"
></input>
</div>
)
};
export default SignUpPopup;
Any help or guidance to the right path is greatly appreciated!

You can validate age on onChange of input
const onChange = (e) => {
const currentYear = new Date().getFullYear();
const year = e.target.value.split("-")[0];
const age = currentYear - year;
if (age < 18) setError("Invalid age");
}
<input
type="date"
className="form-control shadow-none"
placeholder="mm/dd/yyyy"
aria-describedby="button-addon2"
onChange={onChange}
/>

Related

Submitting dynamically created form to database in reactJS

I am trying to insert the values through this dynamic form but I am only able to insert just one entry (even though I enter multiple forms) and the values that are getting inserted are 0 (in the database as well).
I am passing the index still I am not getting the desired output. The list looks like this:
List of the entered details
The previous entry was entered manually.
This is the CODE through which I submit values.
import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate, useParams } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';
const RoomInfo = () => {
const [shared_no] = useState();
const [no_of_rooms] = useState();
const [rent_per_month] = useState();
const [vacancy] = useState();
const [total_capacity] = useState();
const [pg_fid, setpgfid] = useState();H
let handleChange = (i, e) => {
let newFormValues = [...formValues]; /** makes a copy of the current form values and assign it to newFormValues **/
newFormValues[i][e.target.name] = e.target.value;
setFormValues(newFormValues);
}
const navigate = useNavigate();
let addFormFields = () => {
setFormValues([...formValues, { shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}])
};
let removeFormFields = (i) => {
let newFormValues = [...formValues];
newFormValues.splice(i, 1);
setFormValues(newFormValues)
}
const [formValues, setFormValues] = useState([{ shared_no: "", no_of_rooms: "", rent_per_month: "", total_capacity: "", vacancy: "" }])
/*const [settotal_no_of_rooms] = useState('1');
const [setrooms_entered] = useState('1');
const getTotalCapacity = () => {
return formValues.reduce((total,element) => {
return total + Number(element.shared_no) * Number(element.no_of_rooms);
}, 0);
};*/
const resetForm = () => setFormValues([{shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}]);
const Total_no_of_rooms_entered = () => {
return formValues.reduce((total, element) => {
return total + Number(element.no_of_rooms);
}, 0);
};
const saveRoomInfo = (e) =>{
e.preventDefault();
const roominfo = [...formValues];
RoomInfoService.createRoomInfo(roominfo).then((response) => {
console.log(response.data);
navigate('/listroominfo');
}).catch(error =>{
console.log(error);
})
}
return (
<>
<div className='heading'>
<h1 style={{ marginBottom: '50px' }}>Enter Your PG Room Details</h1>
</div>
<form>
<div className="form-inline" style={{ marginBottom: '50px' }}>
{/*<label>Total of Rooms: </label>
<input type="number" name="total_no_of_rooms" style={{ width: '90px' }} onClick={(e) => settotal_no_of_rooms(e.target.value)} defaultValue={1} /> */}
<label>Rooms Entered:</label>
<div><input type="number" name="rooms_entered" value={Total_no_of_rooms_entered()} readOnly></input></div>
</div>
</form>
<div>
<form>
{formValues.map((element, index) => (
<div className="form-inline" key={index} style={{ borderBottom: '1px solid black' }}>
<label>Sharing Number</label>
<select id="shared_no" name="shared_no" title="no of shared rooms" value={element.shared_no || ""} onChange={e => handleChange(index, e)} >
<option value="">---Select---</option>
<option value="1">Single Sharing</option>
<option value="2">Two Bed Sharing</option>
<option value="3">Three Bed Sharing</option>
<option value="4">Four Bed Sharing</option>
<option value="5">Five Bed Sharing</option>
</select>
<label> No of Rooms:</label>
<input type="number" style={{ width: '60px' }} name="no_of_rooms" value={element.no_of_rooms || ""} onChange={e => handleChange(index, e)}></input>
<label> Rent per month:</label>
<input type="number" style={{ width: '100px' }} name="rent_per_month" value={element.rent_per_month || ""} onChange={e => handleChange(index, e)}></input>
<label> Total Capacity:</label>
<input type="number" style={{ width: '80px' }} name="total_capacity" value={element.total_capacity} onChange={e => handleChange(index, e)}></input>
<label> Vacancy:</label>
<input type="number" style={{ width: '50px' }} name="vacancy" value={element.vacancy || ""} onChange={e => handleChange(index, e)}></input>
{
index ?
<button type="button" className="button-remove" onClick={() => removeFormFields(index)}><ImBin size={20}/></button>
: null
}
</div>
))}
<div className="button-section">
<button className="button" type="button" onClick={() => addFormFields()}>Add</button>
<button className="button" type="button" onClick={resetForm}>Reset</button>
<button className="button" type="submit" onClick={(e) => saveRoomInfo(e)}>Submit</button>
</div>
</form>
</div>
</>
)
}
export default RoomInfo
Reference of Dynamic Form
The issue is while I am fetching the data from the form. But I can't figure it out. Thank you.

How i can implement redux saga concept in login page react

Here how can i implement this login page using Redux saga concept. I also attached my codesandbox link below. Please provide any ideas to implement using redux saga concept.
For what purpose we mainly use redux saga concepts in react. Please provide any articles for learning redux saga.
https://codesandbox.io/s/inspiring-rain-olm7wx?file=/src/components/Login.jsx
import React from "react";
import { connect } from "react-redux";
import { loginAction } from "../actions/loginAction";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
const emailValidator = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const passwordValidator = /(?=.*[a-z])/;
function Login(props) {
let navigate = useNavigate();
const isLogin = useSelector((state) => state.login.isLogin);
useEffect(() => {
if (isLogin) {
navigate("/");
}
}, [isLogin]);
const [state, setState] = useState({
email: "",
password: "",
emailAddressError: "",
passwordError: "",
isLogin: false,
isFormSubmitted: false
});
const handleChange = (event) => {
const { name, value } = event.target;
setState((prev) => ({ ...prev, [name]: value }));
return;
};
const handleBlur = (event) => {
const { name } = event.target;
validateField(name);
return;
};
const handleSubmit = (event) => {
event.preventDefault();
var data = {
email: state.email,
password: state.password
};
let formFileds = ["email", "password"];
let isValid = true;
formFileds.forEach((field) => {
isValid = validateField(field) && isValid;
});
if (isValid) {
setState((prev) => ({ ...prev, isFormSubmitted: true }));
const dispatch = props.dispatch;
dispatch(loginAction.login(data));
} else setState((prev) => ({ ...prev, isFormSubmitted: false }));
return state.isFormSubmitted;
};
const validateField = (name) => {
let isValid = false;
if (name === "email") isValid = validateemail();
else if (name === "password") isValid = validatePassword();
return isValid;
};
const validateemail = () => {
let emailAddressError = "";
const value = state.email;
if (value.trim() === "") emailAddressError = "Email Address is required";
else if (!emailValidator.test(value))
emailAddressError = "Email is not valid";
setState((prev) => ({ ...prev, emailAddressError }));
return emailAddressError === "";
};
const validatePassword = () => {
let passwordError = "";
const value = state.password;
if (value.trim() === "") passwordError = "Password is required";
else if (!passwordValidator.test(value))
passwordError = "Password contains small character only";
setState((prev) => ({ ...prev, passwordError }));
return passwordError === "";
};
return (
<div>
<div>
<div class="no-gutters row" style={{ height: "100vh" }}>
<div class="d-flex flex-column justify-content-center align-items-center h-100 col-12 col-md-6">
<div class="container">
<div class="d-flex justify-content-center row">
<div class="col-auto col-lg-8">
<h5 class="fw-bold mb-5">Login</h5>
<form className="form" onSubmit={handleSubmit}>
<div class="form-group">
<label class="form-label">
<b>Email</b>
</label>{" "}
<span style={{ color: "red" }}> *</span>
<input
type="text"
class="form-control"
label="email"
name="email"
value={state.email}
onChange={handleChange}
placeholder="email"
onBlur={handleBlur}
autoComplete="off"
/>
{state.emailAddressError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.emailAddressError}
</div>
)}
</div>
<div class="Login_formGroup__3wtgQ form-group">
<label class="form-label">
<b>Password</b>
</label>{" "}
<span style={{ color: "red" }}> *</span>
<input
type="password"
class="form-control"
variant="outlined"
id="outlined-basic"
label="password"
name="password"
value={state.password}
onChange={handleChange}
placeholder="password"
onBlur={handleBlur}
autoComplete="off"
/>
{state.passwordError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.passwordError}
</div>
)}
</div>
<div class="d-flex justify-content-between align-items-center mt-5">
<button
class="btn "
style={{ backgroundColor: "#bd744c", color: "white" }}
>
<b>LOGIN</b>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
const mapStateToProps = (state) => {
return {
token: state.login.token
};
};
export default connect(mapStateToProps)(Login);

MERN: best way to validate an Autocomplete control

I'm working on user input validation, I'm having problems with the Autocomplete, so far I'm focus on evaluate if the associated TextField is empty, this is the code snippet:
<div className={clientMethodPaymentControlClasses}>
<label htmlFor="clientMethodPayment">Method of Payment *</label>
<Autocomplete
options={paymentMethods}
style={{ width: 300 }}
autoHighlight
renderInput={(params) => (
<TextField
id="clientMethodPayment"
{...params}
variant="outlined"
autocomplete="off"
ref={clientMethodPaymentRef}
/>
)}
/>
{!formInputsValidity.clientMethodPayment && (
<p>Please choose a method of payment</p>
)}
</div>
I try to catch the control's value using these lines:
const isEmpty = (value) => value.trim() === "";
....
const enteredClientMethodPaymentIsValid = !isEmpty(
enteredClientMethodPayment
);
During the execution I'm getting the error: Uncaught TypeError: value is undefined (related to const isEmpty).
This is the entire code of the component:
import { useRef, useState } from "react";
import TextField from "#material-ui/core/TextField";
import Autocomplete from "#material-ui/lab/Autocomplete";
import classes from "./Orderdetails.module.css";
const isEmpty = (value) => value.trim() === "";
const isNotNineChars = (value) => value.trim().length !== 9;
const paymentMethods = ["Cash", "Credit", "Crypto"];
const OrderDetails = (props) => {
const [formInputsValidity, setFormInputsValidity] = useState({
clientName: true,
clientCellPhone: true,
streetDeliveryAddress: true,
cityDeliveryAddress: true,
postalCodeDeliveryAddress: true,
ordersDeliveryAddress: true,
clientMethodPayment: true,
});
//estos objetos sirven para no capturar todos los keystrokes durante dataInput
const clientNameRef = useRef();
const clientCellPhoneRef = useRef();
const streetDeliveryAddressRef = useRef();
const cityDeliveryAddressRef = useRef();
const postalCodeDeliveryAddressRef = useRef();
const ordersDeliveryAddressRef = useRef();
const clientMethodPaymentRef = useRef();
const ConfirmHandler = (event) => {
event.preventDefault();
const enteredName = clientNameRef.current.value;
const enteredCellPhone = clientCellPhoneRef.current.value;
const enteredOrdersDeliveryAddress = ordersDeliveryAddressRef.current.value;
const enteredStreetDeliveryAddress = streetDeliveryAddressRef.current.value;
const enteredCityDeliveryAddress = cityDeliveryAddressRef.current.value;
const enteredPostalCodeDeliveryAddress =
postalCodeDeliveryAddressRef.current.value;
const enteredClientMethodPayment = clientMethodPaymentRef.current.value;
const enteredNameIsValid = !isEmpty(enteredName);
const enteredCellPhoneIsValid = !isNotNineChars(enteredCellPhone);
const enteredOrdersDeliveryAddressIsValid = !isEmpty(
enteredOrdersDeliveryAddress
);
const enteredStreetDeliveryAddressIsValid = !isEmpty(
enteredStreetDeliveryAddress
);
const enteredCityDeliveryAddressIsValid = !isEmpty(
enteredCityDeliveryAddress
);
const enteredPostalCodeDeliveryAddressIsValid = !isEmpty(
enteredPostalCodeDeliveryAddress
);
const enteredClientMethodPaymentIsValid = !isEmpty(
enteredClientMethodPayment
);
setFormInputsValidity({
clientName: enteredNameIsValid,
clientCellPhone: enteredCellPhoneIsValid,
ordersDeliveryAddress: enteredOrdersDeliveryAddressIsValid,
streetDeliveryAddress: enteredStreetDeliveryAddressIsValid,
cityDeliveryAddress: enteredCityDeliveryAddressIsValid,
postalCodeDeliveryAddress: enteredPostalCodeDeliveryAddressIsValid,
clientMethodPayment: enteredClientMethodPaymentIsValid,
});
const formIsValid =
enteredNameIsValid &&
enteredCellPhoneIsValid &&
enteredOrdersDeliveryAddressIsValid &&
enteredStreetDeliveryAddressIsValid &&
enteredCityDeliveryAddressIsValid &&
enteredPostalCodeDeliveryAddressIsValid &&
enteredClientMethodPayment;
if (!formIsValid) {
return;
}
props.onConfirm({
clientName: enteredName,
clientCellPhone: enteredCellPhone,
ordersDeliveryAddress: enteredOrdersDeliveryAddress,
streetDeliveryAddress: enteredStreetDeliveryAddress,
cityDeliveryAddress: enteredCityDeliveryAddress,
postalCodeDeliveryAddress: enteredPostalCodeDeliveryAddress,
clientMethodPayment: enteredClientMethodPayment,
});
};
const nameControlClasses = `${classes.control} ${
formInputsValidity.clientName ? "" : classes.invalid
}`;
const phoneControlClasses = `${classes.control} ${
formInputsValidity.clientCellPhone ? "" : classes.invalid
}`;
const delivAddressControlClasses = `${classes.control} ${
formInputsValidity.ordersDeliveryAddress ? "" : classes.invalid
}`;
const cityDeliveryAddressControlClasses = `${classes.control} ${
formInputsValidity.cityDeliveryAddress ? "" : classes.invalid
}`;
const streetDeliveryAddressControlClasses = `${classes.control} ${
formInputsValidity.streetDeliveryAddress ? "" : classes.invalid
}`;
const postalCodeDeliveryAddressControlClasses = `${classes.control} ${
formInputsValidity.postalCodeDeliveryAddress ? "" : classes.invalid
}`;
const clientMethodPaymentControlClasses = `${classes.control} ${
formInputsValidity.clientMethodPayment ? "" : classes.invalid
}`;
return (
<form className={classes.form} onSubmit={ConfirmHandler}>
<div className={nameControlClasses}>
<label htmlFor="clientName">Client's Name</label>
<input
type="text"
autoComplete="off"
id="clientName"
ref={clientNameRef}
/>
{!formInputsValidity.clientName && <p>Please Enter a valid Name</p>}
</div>
<div className={phoneControlClasses}>
<label htmlFor="clientCellPhone">Client's Cell Phone Number</label>
<input
type="text"
id="clientCellPhone"
autocomplete="off"
ref={clientCellPhoneRef}
/>
{!formInputsValidity.clientCellPhone && (
<p>Please Enter a 8 digits numbers</p>
)}
</div>
<div className={delivAddressControlClasses}>
<label htmlFor="ordersDeliveryAddress">Delivery Address *</label>
<input
type="text"
id="ordersDeliveryAddress"
autocomplete="off"
ref={ordersDeliveryAddressRef}
/>
{!formInputsValidity.ordersDeliveryAddress && (
<p>Please Enter a valid address</p>
)}
</div>
<div className={cityDeliveryAddressControlClasses}>
<label htmlFor="cityDeliveryAddress">City Delivery Address *</label>
<input
type="text"
id="cityDeliveryAddress"
autocomplete="off"
ref={cityDeliveryAddressRef}
/>
{!formInputsValidity.cityDeliveryAddress && (
<p>Please Enter a valid city name</p>
)}
</div>
<div className={streetDeliveryAddressControlClasses}>
<label htmlFor="streetDeliveryAddress">Street Delivery Address *</label>
<input
type="text"
id="streetDeliveryAddress"
autocomplete="off"
ref={streetDeliveryAddressRef}
/>
{!formInputsValidity.streetDeliveryAddress && (
<p>Please Enter a valid street name</p>
)}
</div>
<div className={postalCodeDeliveryAddressControlClasses}>
<label htmlFor="postalCodeDeliveryAddress">
Postal Code Delivery Address *
</label>
<input
type="text"
id="postalCodeDeliveryAddress"
autocomplete="off"
ref={postalCodeDeliveryAddressRef}
/>
{!formInputsValidity.postalCodeDeliveryAddress && (
<p>Please Enter a valid Postal Code</p>
)}
</div>
<div className={clientMethodPaymentControlClasses}>
<label htmlFor="clientMethodPayment">Method of Payment *</label>
<Autocomplete
options={paymentMethods}
style={{ width: 300 }}
autoHighlight
renderInput={(params) => (
<TextField
id="clientMethodPayment"
{...params}
variant="outlined"
autocomplete="off"
ref={clientMethodPaymentRef}
/>
)}
/>
{!formInputsValidity.clientMethodPayment && (
<p>Please choose a method of payment</p>
)}
</div>
<div className={classes.actions}>
<button type="button" onClick={props.onCancel}>
Close
</button>
<button>Confirm Order</button>
</div>
</form>
);
};
export default OrderDetails;
My questions are:
is it a good approach trying to validate the related Textfield of Autocomplete?
what should be the best way to validate if the Autocomplete control is Empty?
Thanks in advance.

Im facing error in firstname ,lastname required in my code. It is not showing those errors

Here for email, password and confirm password error messages are showing but for firstname, phone number and lastname the error is not showing. How can I find out what that error is?
For email when I click on that field and do not give any value, it is showing an error and the same thing for firstname.
import React from "react";
import { useState } from "react";
const emailValidator = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
function Register(props) {
const [state, setState] = useState({
email: "",
emailAddressError: "",
firstName: "",
firstNameError: ""
});
const handleChange = (event) => {
const { name, value } = event.target;
setState((prev) => ({ ...prev, [name]: value }));
return;
};
const handleBlur = (event) => {
const { name } = event.target;
validateField(name);
return;
};
const handleSubmit = (e) => {
e.preventDefault();
let formFileds = ["email", "firstName"];
let isValid = true;
formFileds.forEach((field) => {
isValid = validateField(field) && isValid;
});
if (isValid) setState((prev) => ({ ...prev, isFormSubmitted: true }));
else setState((prev) => ({ ...prev, isFormSubmitted: false }));
return state.isFormSubmitted;
};
const validateField = (name) => {
let isValid = false;
if (name === "email") isValid = validateemail();
else if (name === "firstName") isValid = validatefirstName();
return isValid;
};
const validatefirstName = () => {
let firstNameError = "";
const value = state.firstName;
if (value.trim() === "") firstNameError = "First Name is required";
setState((prev) => ({ ...prev, firstNameError }));
return firstNameError === "";
};
const validateemail = () => {
let emailAddressError = "";
const value = state.email;
if (value === "") emailAddressError = "Email Address is required";
else if (!emailValidator.test(value))
emailAddressError = "Email is not valid";
setState((prev) => ({ ...prev, emailAddressError }));
return emailAddressError === "";
};
return (
<div id="__next">
<div class="no-gutters row" style={{ height: "100vh" }}>
<div class="d-flex flex-column justify-content-center align-items-center h-100 col-12 col-md-6">
<div class="container">
<div class="d-flex justify-content-center row">
<div class="col-auto col-lg-8">
<h5 class="fw-bold mb-5">Sign Up</h5>
<form class="w-100">
<div class="d-flex form-group">
<div class="flex-fill mr-5">
<span style={{ color: "red" }}> *</span>
<label for="exampleEmail" class="fw-bold">
First Name
</label>
<input
name="firstName"
value={state.firstName}
onChange={handleChange}
maxLength="20"
class="form-control"
placeholder="First Name"
/>
</div>
{state.firstNameError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.firstNameError}
</div>
)}
</div>
<div class="form-group">
<span style={{ color: "red" }}> *</span>
<label for="exampleEmail" class="fw-bold">
Email
</label>
<input
name="email"
class="form-control"
value={state.email}
onChange={handleChange}
placeholder="Email"
onBlur={handleBlur}
autoComplete="off"
/>
</div>
{state.emailAddressError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.emailAddressError}
</div>
)}
<div class="d-flex justify-content-between align-items-center mt-5">
<a
href="/login"
style={{ textDecoration: "none", color: "#bd744c" }}
>
{" "}
</a>
<button
class="btn "
style={{ backgroundColor: "#bd744c", color: "white" }}
onSubmit={handleSubmit}
>
<b>SIGN UP</b>
</button>
</div>
</form>
<br />
</div>
</div>
</div>
</div>
<div class="d-none d-md-inline-block h-100 Register_backgroundImage__2j-eI col-sm-6"></div>
</div>
</div>
);
}
// export default Register;
export default Register;
You forgot to call onBlur={handleBlur} in firstName and I have made small changes in your code:
Now it will show errors when you click on submit.

i want to integrate backend codes i.e. rest api to front end reactjs code

i want to integrate backend codes i.e. rest api to front end reactjs code. i have tried usingaxios . pls help i am new to react.
the code is below:
import React, { useState } from "react";
import "./Register.css";
import { useHistory } from "react-router-dom";
import axios from "axios";
function Register() {
const history = useHistory();
const [data, setData] = useState({
name: "",
phone: "",
password: "",
confirmpassword: "",
});
const [nameErr, setNameErr] = useState({});
const [phoneErr, setPhoneErr] = useState({});
const [passwordErr, setPasswordErr] = useState({});
const [confirmPasswordErr, setConfirmPasswordErr] = useState({});
const InputEvent = (event) => {
const { name, value } = event.target;
setData((preVal) => {
return {
...preVal,
[name]: value,
};
});
};
const formSubmit = (e) => {
e.preventDefault();
const isValid = formValidation();
if (isValid) {
//if form is valid, route
history.push("/myvehicles");
}
};
const formValidation = () => {
const nameErr = {};
const phoneErr = {};
const passwordErr = {};
const confirmPasswordErr = {};
let isValid = true;
if (data.name.trim().length < 4) {
nameErr.nameShort = "name is short";
isValid = false;
}
if (data.phone.trim().length < 10) {
phoneErr.phoneerror = "phone number must have 10 digits";
}
if (data.password.trim().length < 4) {
passwordErr.passwordShort = "password must be 8 characters";
isValid = false;
}
if (!(data.confirmpassword === data.password)) {
confirmPasswordErr.confirmPasswordError = "password must be same";
isValid = false;
}
setNameErr(nameErr);
setPhoneErr(phoneErr);
setPasswordErr(passwordErr);
setConfirmPasswordErr(confirmPasswordErr);
return isValid;
};
axios.post(`https://localhost:5000/`, { InputEvent }).then((res) => {
console.log(res);
console.log(res.data);
});
return (
<div className="signup__container">
<div className="signup__containerInfo">
<h1 className="h1__swari">सवारी नविकरणको लागि</h1>
<hr />
</div>
<form className="register__form" onSubmit={formSubmit}>
<h5 className="h5__form"> Name</h5>
<input
type="text"
placeholder="पुरा नाम लेख्नुहोस्"
name="name"
value={data.name}
onChange={InputEvent}
/>
{Object.keys(nameErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{nameErr[key]}
</div>
);
})}
<h5 className="h5__form"> phone </h5>
<input
type="text"
placeholder="फोन लेख्नुहोस्"
name="phone"
value={data.phone}
onChange={InputEvent}
/>
{Object.keys(phoneErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{phoneErr[key]}
</div>
);
})}
<h5 className="h5__form"> Password </h5>
<input
type="Password"
placeholder="पासवर्ड लेख्नुहोस्s"
name="password"
value={data.password}
onChange={InputEvent}
/>
{Object.keys(passwordErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{passwordErr[key]}
</div>
);
})}
<h5 className="h5__form"> Confirm Password </h5>
<input
type="Password"
placeholder="पुन: पासवर्ड लेख्नुहोस्"
name="confirmpassword"
value={data.confirmpassword}
onChange={InputEvent}
/>
{Object.keys(confirmPasswordErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{confirmPasswordErr[key]}
</div>
);
})}
<p>
<button type="submit" className="signup__registerButton">
Register Now
</button>
</p>
</form>
</div>
);
}
export default Register;
the code is as above . i want the register auth which is token based and wanted to call from the backend and the also send form values to the backend how can i do it?

Resources