When the form is empty, pressing the Login button opens the page. I want him to make a mistake. I'm already getting an error if it's not compatible with the server. How can I solve this problem ?
const login = (e) => {
e.preventDefault();
axiox.post("http://localhost:2000/api/auth/login", {
email,
password
}).then((response) => {
console.log("response", response)
localStorage.setItem("login", JSON.stringify({
userLogin: true,
token: response.data.access_token,
}));
setError("");
setEmail("");
setPassword("");
history.push("schools");
})
.catch((error) => setError(error.response.data.message));
};
CodePudding user response:
use this to validate the form
const login = (e) => {
e.preventDefault();
if(!email || !password){
//send error message to user
}else{
// make request to api
}
};
CodePudding user response:
A simple and efficient way is to check any errors at the client-side i.e if the form is empty you should not make an API call. The validation on the form or in your function to check if the values are null is enough.
You can add more validations on the form, however, certain validations which are business mandate could be done at the server-side.
const login = (e) => {
e.preventDefault();
// make request to api
if(!email && !password) {
//here make the API call to authenticate a user
}
};
Check this link to get more details, how to add the validation in React Forms.
CodePudding user response:
I think you want the form to respond with an error message when they haven't filled up the form. Here:
const login = (e) => {
e.preventDefault();
if(!email || !password){
//Send the error message, like alert('Either the Email or Password is empty!')
}else{
//The code to execute when both Email and Password are filled.
}
};
