Home > Enterprise >  React Native or React. Validate inputs
React Native or React. Validate inputs

Time:08-15

I have three inputs in the form. When I submit the form, I want to check, if this inputs are not empty. But after submitting empty form only last input has error style. I want all three inputs to have error style. My code:

const [name, setName] = useState(null)
const [email, setEmail] = useState(null)
const [message, setMessage] = useState(null)

const [style, setStyle] = useState({
    name : null,
    email : null,
    message : null,
    
})

const sendEmail = async () => {

    setStyle({
        ...style,
        name: null,
        email: null,
        message: null
    })
        
        if(!name || !email || !message){ 
            if(!name) {
                setStyle({
                    ...style, 
                    name: gStyle.inputError
                })
            }
            if(!email) {
                setStyle({
                    ...style, 
                    email: gStyle.inputError
                })
            }  
            if(!message) {
                setStyle({
                    ...style, 
                    message: gStyle.inputError
                })
            }                
        }
        
        else {/*do smth*/}
    }        
}

And here is my view in compo:

<View>
     <TextInput onChangeText={(value) => {setName(value)}} />
     <TextInput onChangeText={(value) => {setEmail(value)}} />
     <TextInput onChangeText={(value) => {setMessage(value)}} />
                        
     <TouchableOpacity onPress={() => sendEmail()}>
         <Text>Send</Text>
     </TouchableOpacity>
</View>

CodePudding user response:

Instead of setting state at every if condition, create an empty style obj in sendEmail function , push error style at every condition in the style obj. Like

const errorStyles={};
 if(condition)
errorStyles.name=gStyles.error;

At last set styles state with the errorStyles obj Like

setStyle(errorStyles);

Try that and see if it works .Other then that where are the styles being applied on the text input ?

  • Related