'Looking for help in dealing with form validation conditionals with required, URL format and both in React before Submit
I'm creating a form that checks for required fields, proper url format or both. I'm skipping onFocus and onBlur for now and only handle the format errors on submit. If there are issues, a message is displayed for each field that has an issue. Otherwise, if no issues, go ahead and submit.
I'm having issues getting the conditionals where a non-required field might be empty so it shouldn't be a problem but is anyway. And also what will satisfy the conditions to submit.
my useState hooks are for error handling are like so:
const [inputErrors, setInputErrors] = useState({
logoUrl: false // required
name: false // required
})
const [formatErrors, setFormatErrors] = useState({
logoUrl: false // also needs proper url format
homePageUrl: false // needs proper url format but not required
})
Then is within my submit function:
if (!logoUrl.length) {
setInputErrors((prevState) => ({
...prevState,
logoUrl: true
})
} else {
setInputErrors((prevState) => ({
...prevState,
logoUrl: false
)}
}
if (!urlValidation(logoUrl) {
setFormatErrors((prevState) => ({
...prevState,
logoUrl: true
})
} else {
setInputErrors((prevState) => ({
...prevState,
logoUrl: false
)}
}
if (!name.length) {
setInputErrors((prevState) => ({
...prevState,
name: true
})
} else {
setInputErrors((prevState) => ({
...prevState,
name: false
)}
}
if (!homePageUrl.length && !urlValidation(homePageUrl) {
setFormatErrors((prevState) => ({
...prevState,
homePageUrl: true
})
} else {
setInputErrors((prevState) => ({
...prevState,
homePageUrl: false
)}
}
If none of the above are true then submit form. If not, show the user the corresponding error message per input using conditionals in the JSX.
Since all of these if statements need to be hit, how do I make an ok'd submit part of the equation.
I've tried to allow a submit if !Object.values(inputErrors).filter(err => err === true).length and !Object.values(formatErrors).filter(err => err === true).length but the problem is that, within the same function, the state of errors won't be reflected because of closure.
Also, if a non-required url format is empty, it shouldn't throw an error.
Ultimately the submit would send data and reset the error state fields to false.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
