简体   繁体   中英

Every IF statement is not executing in my React code

I am writing a form validation script in React but inside a function I have put multiple if statement. All the if/else statement supposed to be executed but only the final if statement is executing. What am I doing wrong? please help. I provided the code below.

const onSubmitHandle = () => {

    if (name.length===0) {
        setErr ({ ...err,
            nameText:'Please enter name'
        })
    } else {
        setErr ({ ...err,
            nameText:''
        })
    };

    if (number.length<=5) {
        setErr ({ ...err,
            numberText:'Please enter a valid number'
        })
    } else {
        setErr ({ ...err,
            numberText:''
        })
    };

    if (email.length===0) {
        setErr ({ ...err,
            emailText:'Please enter email'
        })
    } else {
        setErr ({ ...err,
            emailText:''
        })
    };

    if(err.emailText.length===0 && err.nameText.length===0 && err.serviceText.length===0 && err.budgetText.length===0 && err.numberText.length===0) {
        alert('Your request is succesfully submited. We will reach you soon')
        setName('');
        setService('');
        setBudget('');
        setNumber('');
        setEmail('');
    };
}

Please help

So it seems you are spreading the err variable wrong, i think what you want is:

setErr ({ 
   err:{
     ...err,
     emailText:'yadayadayada'
   }
})

by doing this you create a new var err with the old properties and still add a new one that you want (read up on spread operator) and you were right in this example it is not needed the return since you want to run all verifications

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM