表單少不了的要做一下錯誤題式訊息,在之前的登入註冊頁面使用firebase
時then
後面接的catch
就是用在這邊。
//login.js
const [emailErrorMessage,setEmailErrorMessage]=useState('');
const [passwordErrorMessage,setPasswordErrorMessage]=useState('');
function onSubmit(){
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
var user = userCredential.user;
navigate("/")
})
.catch((error) => {
var errorCode = error.code;
console.log(errorCode)
switch(errorCode){
case 'auth/invalid-login-credentials':
setEmailErrorMessage('帳號或密碼錯誤');
setPasswordErrorMessage('帳號或密碼錯誤');
break;
case 'auth/user-not-found':
setEmailErrorMessage('尚未註冊此信箱');
break;
}
});
}
return(
//--略
<div className="form-group">
<label className="form-label" htmlFor="email">帳號<span>*</span></label>
<input className="form-input" id="email" type="email" placeholder="請輸入您註冊的Email" value={email} onChange={ (e) => {setEmail(e.target.value) }}/>
<small>{emailErrorMessage}</small>
</div>
<div className="form-group">
<label className="form-label" htmlFor="password">密碼<span>*</span></label>
<input className="form-input" id="password" type="password" placeholder="至少6字元以上" value={password} onChange={ (e) => {setPassword(e.target.value)}}/>
<small>{passwordErrorMessage}</small>
</div>
)
//signup.js
const [emailErrorMessage,setEmailErrorMessage]=useState('');
const [passwordErrorMessage,setPasswordErrorMessage]=useState('');
function onSubmit(){
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(userCredential => {
var user = userCredential.user;
navigate("/")
})
.catch((error) => {
var errorCode = error.code;
// var errorMessage = error.message;
console.log(errorCode)
switch(errorCode){
case 'auth/email-already-in-use':
setEmailErrorMessage('信箱已存在');
break;
case 'auth/invalid-email':
setEmailErrorMessage('請輸入正確的Email格式');
break;
case 'auth/weak-password':
setPasswordErrorMessage('至少6字元以上');
break;
}
});
};
return(
//--略
<div className="form-group">
<label className="form-label" htmlFor="email">帳號<span>*</span></label>
<input className="form-input" id="email" type="email" placeholder="請輸入您常用的Email" value={email} onChange={(e) => {setEmail(e.target.value) }}/>
<small>{emailErrorMessage}</small>
</div>
<div className="form-group">
<label className="form-label" htmlFor="password1">密碼設定<span>*</span></label>
<input className="form-input" id="password1" type="password" placeholder="至少6字元以上" value={password} onChange={ (e) => {setPassword(e.target.value)}}/>
<small>{passwordErrorMessage}</small>
</div>
)
這邊(連結)是所以錯誤訊息errorCode,如果有想添加其他的可以在這找找。
今天是幸運的一天,沒有出現錯誤訊息!!