I am trying to validate form using useState() and useEffect()
Here's my useEffect() method:
/ for every change in our state this will be fired
// we add validation here and disable the save button if required
useEffect(() => {
// we want to skip validation on first render
if (firstRender.current) {
firstRender.current = false
return
}
// here we can disable/enable the save button by wrapping the setState function
// in a call to the validation function which returns true/false
//setDisabled(formValidation())
formValidation();
}, [fullName,email,password]) // any state variable(s) included in here will trigger the effect to run
`I am new to React JS so have done basic coding using if-else. I am stuck in the concept here more than the technology. I am unable to validate other input fields such as email and password. How to achieve that? Here's my validation method: // here we run any validation, returning true/false
const formValidation = () => {
var error = false;
if (fullName === "") {
setNameError('Name cant be blank!')
error = true;
}
let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!regEmail.test.email) {
setEmailError('Enter a valid email id')
error = true;
}
if (email === "") {
setEmailError('Mandatory Field')
error = true;
}
let regPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
if (!regPassword.test.email) {
// alert("errosdr")
setPasswordError('Invalid Password Format')
error = true;
}
if (error == true) {
return true;
}
else {
setNameError(null)
setEmailError(null)
setPasswordError(null)
return false
}
}
The validation for the first field works well i.e. fullName.
Just for reference, here's the definition for useState()
// we use the help of useRef to test if it's the first render
const firstRender = useRef(true);
// set a state variable which can be used to disable the save/submit button
// we set it to true so that the form is disabled on first render
const [disable, setDisabled] = useState(true);
// set error messages to display to the user
const [nameError, setNameError] = useState(null);
const [emailError, setEmailError] = useState(null);
const [passwordError, setPasswordError] = useState(null);
// set initial state value(s)
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
I am trying to validate form using useState() and useEffect()
Here's my useEffect() method:
/ for every change in our state this will be fired
// we add validation here and disable the save button if required
useEffect(() => {
// we want to skip validation on first render
if (firstRender.current) {
firstRender.current = false
return
}
// here we can disable/enable the save button by wrapping the setState function
// in a call to the validation function which returns true/false
//setDisabled(formValidation())
formValidation();
}, [fullName,email,password]) // any state variable(s) included in here will trigger the effect to run
`I am new to React JS so have done basic coding using if-else. I am stuck in the concept here more than the technology. I am unable to validate other input fields such as email and password. How to achieve that? Here's my validation method: // here we run any validation, returning true/false
const formValidation = () => {
var error = false;
if (fullName === "") {
setNameError('Name cant be blank!')
error = true;
}
let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!regEmail.test.email) {
setEmailError('Enter a valid email id')
error = true;
}
if (email === "") {
setEmailError('Mandatory Field')
error = true;
}
let regPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
if (!regPassword.test.email) {
// alert("errosdr")
setPasswordError('Invalid Password Format')
error = true;
}
if (error == true) {
return true;
}
else {
setNameError(null)
setEmailError(null)
setPasswordError(null)
return false
}
}
The validation for the first field works well i.e. fullName.
Just for reference, here's the definition for useState()
// we use the help of useRef to test if it's the first render
const firstRender = useRef(true);
// set a state variable which can be used to disable the save/submit button
// we set it to true so that the form is disabled on first render
const [disable, setDisabled] = useState(true);
// set error messages to display to the user
const [nameError, setNameError] = useState(null);
const [emailError, setEmailError] = useState(null);
const [passwordError, setPasswordError] = useState(null);
// set initial state value(s)
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
Share
Improve this question
asked Jul 4, 2020 at 9:12
sakshinarangsakshinarang
993 silver badges14 bronze badges
2
-
use
Formik
withyup
library for easier validation a form handling. – adel Commented Jul 4, 2020 at 10:06 - @adel Thanks for informing. For now, wish to do it the normal way. :) – sakshinarang Commented Jul 4, 2020 at 12:05
1 Answer
Reset to default 5As soon as you call a set function in a ponent, it automatically re-renders. So in your case, formValidation
calls setNameError
and proceeds to re-rendering, thus the rest of the code was not executed.
In your current implementation, this is what happened:
fullName
,email
, orpassword
is changedformValidation()
is called- checks if
fullName === ""
and callssetNameError("Name can't be blank!")
- ponent re-renders
- the rest of the logic in the function was not called.
To avoid this, you might want to store your error states in a single state:
const [errors, setErrors] = useState({})
The best practice is to only call a single setState
in every function you create in every ponent. Ideally it is called after a certain logic.
Here is a sample modified formValidation
const formValidation = () => {
let newErrors = {}
if (fullName === "") {
newErrors.name = 'Name cant be blank!'
}
let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!regEmail.test.email) {
newErrors.email = 'Enter a valid email id'
}
if (email === "") {
newErrors.email = 'Mandatory Field'
}
let regPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
if (!regPassword.test.email) {
newErrors.password = 'Invalid Password Format'
}
setErrors(newErrors)
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745262585a4619279.html
评论列表(0条)