Handling multiple input errors
Hello I have a question is there way to handle these inputs in the nice way for the user. Like name must contains only letters, postal code is five character etc. My point is to avoid 'if statement' snake but I have no idea how. Maybe should I stay with 'if statement' spaghetti and it is okay. I know I put these errors inside ReducerValue and then handle them in the reducer. But it does not make "if" statement disappear.
const initialReducerValue = {
name: {
val: '',
isValid: false,
},
lastName: {
vaL: '',
isValid: false
},
phoneNumber: {
val: '',
isValid: false
},
city: {
val: '',
isValid: false,
},
street: {
val: '',
isValid: false
},
postal: {
val: '',
isValid: false
},
}
const OrderForm = () => {
const cartItems = useSelector(state => state.cart.items)
let nameError;
let lastNameError;
let phoneNumberError;
let cityError;
let streetError;
let postalError
const orderReducer = (state, action) => {
if (action.type === 'HANDLE TEXT CHANGE') {
let inputIsValid = false
if (action.payload.trim().length === 0) inputIsValid = false
if (action.payload.trim().length > 0) inputIsValid = true
return {
...state,
[action.field]: {
val: action.payload,
isValid: inputIsValid
}
}
}
}
Solution 1:
It's so nice to say 'No'to if conditions for forms. I have some better solutions to avoid those.
- Formik
- React hook form
You can use any one of the libraries to handle forms & their validation. For advanced validations, you can use Yup.
Refer more here