'Using switch case to validate form
I am creating a form validation with 2 conditions to validate. Is this a good way to use switch case with if else statement? Or is this something that is frown upon? If so, what would a better way to approach this without using external library, thank you.
Code:
const validate = ( name, value) => {
switch (name) {
case "user_name":
if (!value) {
setErrors({ ...errors, user_name: "Please, submit required data" });
} else if (!new RegExp(/^[A-Za-z0-9]+$/).test(value)) {
setErrors({
...errors,
user_name: "Please, provide the data of indicated type(no special characters)",
});
} else {
let newObj = omit(errors, "user_name");
setErrors({ ...newObj });
}
break;
.....
Solution 1:[1]
It's not very readable so I wouldn't say it's the best way, but it's definitely not the worst. You could try something like this.
const validate = (name, value) => {
if (!value) {
setErrors({ ...errors, [name]: "Please, submit required data" })
return
}
switch (name) {
case "user_name": {
if (!new RegExp(/^[A-Za-z0-9]+$/).test(value)) {
setErrors({
...errors,
user_name: "Please, provide the data of indicated type(no special characters)"
})
return
}
}
}
const newObj = omit(errors, name)
setErrors({ ...newObj })
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | timpa |
