Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Native or React. Validate inputs

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 ?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading