fix: Update password validation logic

This commit is contained in:
Peter Carl Pardo committed 2024-12-04 23:52:38 +08:00
1 parent a6c91648c5
commit 6fa26ff5ab
1 file changed
+33 -21
@@ -10,6 +10,13 @@ import Alert from "../../Alert";
import { update } from "../../../Features/Auth/authSlice"; import { update } from "../../../Features/Auth/authSlice";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { getTouchedFieldErrors } from "../../../Validation/error";
const defaultPasswordsState = {
password: "",
newPassword: "",
confirm: "",
};
/** /**
* PasswordPanel component manages the form for editing password. * PasswordPanel component manages the form for editing password.
@@ -30,35 +37,40 @@ const PasswordPanel = () => {
"edit-confirm-password": "confirm", "edit-confirm-password": "confirm",
}; };
const [localData, setLocalData] = useState({ const [localData, setLocalData] = useState(defaultPasswordsState);
password: "", const [errors, setErrors] = useState(defaultPasswordsState);
newPassword: "", const [touchedFields, setTouchedFields] = useState({
confirm: "", password: false,
newPassword: false,
confirm: false,
}); });
const [errors, setErrors] = useState({});
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
const name = idToName[id]; const name = idToName[id];
setLocalData((prev) => ({
...prev, const updatedData = {
...localData,
[name]: value, [name]: value,
})); };
const updatedTouchedFields = {
...touchedFields,
[name]: true,
};
const validation = credentials.validate( const validation = credentials.validate(
{ [name]: value }, { ...updatedData },
{ abortEarly: false, context: { password: localData.newPassword } } { abortEarly: false, context: { password: updatedData.newPassword } }
); );
setErrors((prev) => { const updatedErrors = getTouchedFieldErrors(validation, updatedTouchedFields);
const updatedErrors = { ...prev };
if (validation.error) { if (!touchedFields[name]) {
updatedErrors[name] = validation.error.details[0].message; setTouchedFields(updatedTouchedFields);
} else { }
delete updatedErrors[name];
} setLocalData(updatedData);
return updatedErrors; setErrors(updatedErrors);
});
}; };
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
@@ -220,8 +232,8 @@ const PasswordPanel = () => {
loading={isLoading} loading={isLoading}
loadingIndicator="Saving..." loadingIndicator="Saving..."
disabled={ disabled={
Object.keys(errors).length !== 0 || Object.keys(errors).length > 0 ||
Object.values(localData).filter((value) => value !== "").length === 0 Object.values(localData).filter((value) => value === "").length > 0
} }
sx={{ sx={{
px: theme.spacing(12), px: theme.spacing(12),