'Error not showing up while some fields are not entered when submitted
The form using react functional component doesnot show errors when a field is empty. When I submit name field without entering anything for the first time it shows error message asking to enter the name.If I enter a name the error stops showing.But when I backspace to clear the name field and make it empty the error is not showing up. Why is this happening?What's wrong with the code?
I have tried using useffect then also it is not showing errors or not checking whether the name field is empty.
const[state,setState]= useState({
name: "",
email: "",
password: "",
})
const[errors,setErrors]= useState("")
const { name, email, password, error,loading} = state
const handleChange =(e) =>{
setState({ ...state, [e.target.name] : [e.target.value]})
}
// console.log(name);
const validateForm = () => {
let errors = {};
let formIsValid = true;
if (!name ) {
formIsValid = false;
errors["name"] = "*Please enter your name.";
console.log(name);
}
if (name) {
if (!name.toString().match(/^[a-zA-Z ]*$/)) {
formIsValid = false;
errors["name"] = "*Please enter alphabet characters only.";
console.log(name);
}
}
if (!email) {
formIsValid = false;
errors["email"] = "*Please enter your email-ID.";
}
if (!password) {
formIsValid = false;
errors["password"] = "*Please enter your password.";
}
if (password) {
if (!password.toString().match(/^.*(?=.{4,})(?=.*\d)(?=.*[a-z]).*$/)) {
formIsValid = false;
errors["password"] = "*Password must contain uppercase,lowercase,symbol and number.";
}
}
setErrors(errors);
return formIsValid;
}
const submituserRegistrationForm =(e) => {
e.preventDefault();
if (validateForm()) {
setState({...state})
console.log(state);
// alert("Form submitted");
});
}
}
useEffect(() => {
validateForm();
}, [state]);
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form method="post" name="userRegistrationForm" onSubmit= {submituserRegistrationForm} >
<h3>Sign Up</h3>
<div className="form-group">
<label>First name</label>
<input type="text" className="form-control" placeholder="First name" name="name" value={name} onChange={handleChange}/>
<div className="errorMsg">{errors.name}</div>
</div>
<div className="form-group">
<label>Email address</label>
<input type="email" className="form-control" placeholder="Enter email" name="email" value={email} onChange={handleChange} />
<div className="errorMsg">{errors.email}</div>
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" name="password" value={password} onChange={handleChange}/>
<div className="errorMsg text-muted">{errors.password}</div>
</div>
<button type="submit" className="btn btn-primary btn-block" value="Register">Sign Up</button>
</form>
</div>
</div>
)
}
`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
