Skip to content

Commit 324cc46

Browse files
overall form validation and refractoring code
1 parent 4846ef9 commit 324cc46

File tree

3 files changed

+64
-42
lines changed

3 files changed

+64
-42
lines changed

.eslintcache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
[{"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\index.js":"1","E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\App.js":"2","E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\components\\SimpleInput.js":"3"},{"size":142,"mtime":1616579686000,"results":"4","hashOfConfig":"5"},{"size":168,"mtime":1616579782000,"results":"6","hashOfConfig":"5"},{"size":2575,"mtime":1632831679064,"results":"7","hashOfConfig":"5"},{"filePath":"8","messages":"9","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"10"},"eoqf54",{"filePath":"11","messages":"12","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"10"},{"filePath":"13","messages":"14","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\index.js",[],["15","16"],"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\App.js",[],"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\components\\SimpleInput.js",[],{"ruleId":"17","replacedBy":"18"},{"ruleId":"19","replacedBy":"20"},"no-native-reassign",["21"],"no-negated-in-lhs",["22"],"no-global-assign","no-unsafe-negation"]
1+
[{"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\index.js":"1","E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\App.js":"2","E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\components\\SimpleInput.js":"3"},{"size":142,"mtime":1616579686000,"results":"4","hashOfConfig":"5"},{"size":168,"mtime":1616579782000,"results":"6","hashOfConfig":"5"},{"size":2949,"mtime":1632861790351,"results":"7","hashOfConfig":"5"},{"filePath":"8","messages":"9","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"10"},"eoqf54",{"filePath":"11","messages":"12","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"usedDeprecatedRules":"10"},{"filePath":"13","messages":"14","errorCount":0,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\index.js",[],["15","16"],"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\App.js",[],"E:\\JavaScript\\React Course\\apps\\forms-and-validation\\src\\components\\SimpleInput.js",[],{"ruleId":"17","replacedBy":"18"},{"ruleId":"19","replacedBy":"20"},"no-native-reassign",["21"],"no-negated-in-lhs",["22"],"no-global-assign","no-unsafe-negation"]

src/components/SimpleInput.js

Lines changed: 54 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,87 @@
1-
import { useEffect, useRef, useState } from "react";
1+
import {useState } from "react";
22

33
const SimpleInput = (props) => {
4-
const inputRef = useRef();
5-
// for using once
6-
const [enteredName,setEnteredName] = useState('');
4+
const [enteredName, setEnteredName] = useState('');
75
// for storing values after every key stroke
6+
const [enteredEmail, setEnteredEmail] = useState('');
7+
const [enteredEmailTouched, setEnteredEmailTouched] = useState(false);
88

99
//VALIDATION
10-
const [isNameValid, setIsNameValid] = useState(false);//if set to true initially, might create a problem like in useEffect
1110
const [inputTouched, setInputTouched] = useState(false);
1211

13-
useEffect(() => {
14-
if (isNameValid)
15-
console.log("VALID NAME");//in case we might need to send a http request whenever name is valid
16-
},[isNameValid])
12+
const isNameValid = !(enteredName.trim() === "");//since component will be re-rendered after every keystroke
13+
const nameInputInvalid = !isNameValid && inputTouched;
14+
15+
const isEmailValid = enteredEmail.includes('@');
16+
const emailInputInvalid = !isEmailValid && enteredEmailTouched;
1717

18-
const nameInputHandler = event=> {
18+
let isFormValid = false;
19+
if(isNameValid && isEmailValid)
20+
isFormValid = true;
21+
22+
const nameInputHandler = event => {
1923
setEnteredName(event.target.value);
20-
// Remove the error when input becomes valid (validationg after every keystroke)
21-
//we will use event.target.value instead of entered name as state updtaes aren't scheduled by React
22-
//not processed immediately
23-
if (event.target.value.trim() !== "") {
24-
setIsNameValid(true);
25-
}
2624
}
25+
const emailInputChangeHandler = (event) => {
26+
setEnteredEmail(event.target.value);
27+
};
2728
// gets event object by default when binded to the input
2829

2930
// validate OR to show the error when input loses it's focus
3031
const onBlurHandler = () => {
3132
setInputTouched(true);
32-
if (enteredName.trim() === "") {
33-
setIsNameValid(false);
34-
}
3533
}
34+
const emailInputBlurHandler = (event) => {
35+
setEnteredEmailTouched(true);
36+
};
3637

37-
const submitHandler =event => {
38+
const submitHandler = event => {
3839
event.preventDefault();
3940
// by default http request is sent to the server serving this website
4041
// and page will be relaoded, current states will be losed
4142
setInputTouched(true);
42-
if (enteredName.trim() === "") {
43-
setIsNameValid(false);
43+
if (!isNameValid)
4444
return;
45-
}
46-
setIsNameValid(true);
4745
console.log(enteredName);
48-
const inputValue = inputRef.current.value;
49-
console.log(inputValue);
5046
// current property of the refs holds the value assigned to ref
5147
// pointer to the input element holded in current
5248

5349
//Resetting the value
5450
setEnteredName('');
51+
setInputTouched(false);
5552
// inputRef.current.value = ''; WITH refs NOT IDEAL || DONOT MANIPULATE THE REAL DOM
53+
setEnteredEmail('');
54+
setEnteredEmailTouched(false);
5655
}
57-
58-
const nameInputInvalid = !isNameValid && inputTouched;
59-
const formClass = nameInputInvalid ? "form-control invalid" : "form-control";
60-
return (
61-
<form onSubmit={submitHandler}>
62-
<div className={formClass}>
63-
<label htmlFor='name'>Your Name</label>
64-
<input ref={inputRef} type='text' id='name' onChange={nameInputHandler} value={enteredName} onBlur={onBlurHandler}/>
65-
{nameInputInvalid && <p className="error-text">Enter a valid name</p>}
66-
</div>
67-
<div className="form-actions">
68-
<button>Submit</button>
69-
</div>
70-
</form>
71-
);
56+
57+
const nameInputClass = nameInputInvalid ? "form-control invalid" : "form-control";
58+
const emailInputClasses = emailInputInvalid? 'form-control invalid': 'form-control';
59+
60+
return (
61+
<form onSubmit={submitHandler}>
62+
<div className={nameInputClass}>
63+
<label htmlFor='name'>Your Name</label>
64+
<input type='text' id='name' onChange={nameInputHandler} value={enteredName} onBlur={onBlurHandler}/>
65+
{nameInputInvalid && <p className="error-text">Enter a valid name</p>}
66+
</div>
67+
<div className={emailInputClasses}>
68+
<label htmlFor='email'>Your E-Mail</label>
69+
<input
70+
type='email'
71+
id='email'
72+
onChange={emailInputChangeHandler}
73+
onBlur={emailInputBlurHandler}
74+
value={enteredEmail}
75+
/>
76+
{emailInputInvalid && (
77+
<p className='error-text'>Please enter a valid email.</p>
78+
)}
79+
</div>
80+
<div className="form-actions">
81+
<button disabled={!isFormValid}>Submit</button>
82+
</div>
83+
</form>
84+
);
7285
};
7386

7487
export default SimpleInput;

src/index.css

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,15 @@ button:active {
7979
border-color: #33059e;
8080
}
8181

82+
button:disabled,
83+
button:disabled:hover,
84+
button:disabled:active{
85+
background-color: #ccc;
86+
color: #3f3f3f;
87+
border-color: #ccc;
88+
cursor: not-allowed;
89+
}
90+
8291
.form-actions {
8392
text-align: right;
8493
}

0 commit comments

Comments
 (0)