facebook

How to validate user in React Native Apps

By Soumik Hens

How to validate user in React Native Apps

Most of the user dependent apps have a login process in the beginning. This process includes taking credentials from user like user name, password etc. and then verify, validate that credential.

In React Native there are processes to do this. I have done it using my way.

First we have to design the user interface for login. That part is already known to everyone using React Native. Then do the validation and verification of the user credentials. I will show my coding for this.

First of all we need to import some element at the top of the page like shown below

import React, {Component} from ‘react’;
import {
Text,
TextInput,
View,
Button,
Image,
StyleSheet,
KeyboardAvoidingView,
Alert,
CheckBox
} from ‘react-native’;

Here I have used the above mentioned elements for my App. The ‘Component’ and ‘View’ are the mandatory ones. Others are used as they needed further.

Next we need to declare the class that we need to export and inside which we do the rest of the coding except the StyleSheet part.

I have written the class like this-
export default class LoginScreen extends Component {

}

Now, inside this class, first I have declared some state variables like the following –
state = {
user: ”,
namealert:”,
passalert:”,
emailbackgr: false,
passwordbackgr: false,
usernametext:”
};

These variables will be used later on the code.

After this I have declared two customised functions named GetUserDataFunction and UserCheckFunction. I will give the details of the functions after showing the design part a little.

Now we have to write the code for UI inside the render() function like this –
render(){
               return(
                            …
              )
}

Here is my UI part inside the render() function –

<KeyboardAvoidingView style={{flex: 1, justifyContent: ‘center’, alignItems: ‘center’}} behavior=”padding”>
<View style={styles.imgWrap}>
<Image source={require(‘../assets/images/user.png’)} style={{width: ‘90%’, height: ‘90%’}}/>
</View>
<TextInput
style={[styles.textstyle, this.state.emailbackgr?{backgroundColor:’rgba(255,0,0,0.2)’}:{backgroundColor: ‘rgba(31,146,98,0.2)’}]}
placeholder=”Username”
placeholderTextColor={this.state.emailbackgr ? ‘rgba(255,0,0,0.4)’ : ‘rgba(31,146,98,0.4)’}
ref=”username”
onChangeText={(usernametext) => {this.UserCheckFunction(usernametext,’username’),this.setState({usernametext})}}
/>
<View style={{flexDirection: ‘row’}}>
<View style={{width: ‘40%’}}></View>
<View style={styles.alertwrap}>
<Text style={{color: ‘#f00’, fontSize: 12}}>{this.state.namealert}</Text>
</View>
</View>
<TextInput
style={[styles.textstyle, this.state.passwordbackgr?{backgroundColor:’rgba(255,0,0,0.2)’}:{backgroundColor: ‘rgba(31,146,98,0.2)’}]}
placeholder=”Password”
placeholderTextColor={this.state.passwordbackgr ? ‘rgba(255,0,0,0.4)’ : ‘rgba(31,146,98,0.4)’}
ref=”password”
onChangeText={(passwordtext) => this.UserCheckFunction(passwordtext,’password’)}
secureTextEntry={true}
/>
<View style={{flexDirection: ‘row’}}>
<View style={{width: ‘40%’, flexDirection: ‘row’}}>
<CheckBox value={this.state.checked} onValueChange={() => this.setState({ checked: !this.state.checked })}/>
<Text style={{marginTop:5}}>Remember me</Text>
</View>
<View style={styles.alertwrap}>
<Text style={{color: ‘#f00’, fontSize: 12}}>{this.state.passalert}</Text>
</View>
</View>
<View style={{marginTop: 40, width: ‘25%’}}>
<Button title=”Login” color=’#1f9262′ onPress={this.GetUserDataFunction} />
</View>
<View style={{marginTop: 30}}>
<Text>Don’t have an account?
<Text style={{color: ‘#1f9262’}} onPress={()=>this.props.navigation.navigate(‘Signup’)}> Sign Up</Text>
</Text>
</View>
<View style={{marginTop: 3}}>
<Text style={{color: ‘#1f9262’}} onPress={()=>this.props.navigation.navigate(‘Forgot’)}>Forgot password?</Text>
</View>
</KeyboardAvoidingView>

After this I have written the styles like the following –

const styles = StyleSheet.create({
imgWrap:{
width: 150,
height: 150,
borderRadius: 100,
overflow: ‘hidden’,
alignItems: ‘center’,
justifyContent: ‘center’,
marginBottom: 10
},
alertwrap:{
width: ‘40%’,
height: 20,
flexDirection: ‘row’,
justifyContent: ‘flex-end’,
marginTop: 0,
paddingRight: 5
},
textstyle:{
width: ‘80%’,
height: 30,
borderRadius: 10,
paddingLeft: 5,
paddingRight: 5,
paddingTop: 0,
paddingBottom: 0,
color: ‘#1f9262’
}
});

The above mentioned functions are not predefined function like render(). I have written the functions before render().
UserCheckFunction() is used for validating the format of the given credentials.
GetUserDataFunction() is used for verify the user existence.

Here are the functions details –

UserCheckFunction(element,args) {
if(args==’username’ && element==”) {
this.setState({
namealert:’Username is required’,
emailbackgr: true
});
} else if(args==’username’ && element!=”) {
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(reg.test(element) === false){
this.setState({
namealert:’Invalid format’,
emailbackgr: true
});
} else {
this.setState({
namealert:”,
emailbackgr: false
});
}
}
if(args==’password’ && element==”) {
this.setState({
passalert:’Password is required’,
passwordbackgr:true});
} else if(args==’password’ && element!=”) {
this.setState({
passalert:”,
passwordbackgr: false
});
}
}

And

GetUserDataFunction = () =>{
return fetch(‘http://192.168.0.40/reactdbSetup/getuserdata.php’, {
//return fetch(‘/Applications/mongodbase/login’,{
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
email: this.refs.username._lastNativeText,
password: this.refs.password._lastNativeText
})
}).then((response) => response.json()).then((responseJson) => {
if(responseJson.Status===true){
this.setState({user: ‘Welcome ‘ + responseJson.Data.firstname + ‘ ‘ + responseJson.Data.lastname});
this.props.navigation.navigate(‘Profile’, {name: this.state.user});
} else {
if(this.refs.username._lastNativeText == undefined){
this.setState({
namealert:’Username is required’,
emailbackgr: true
});
}
if(this.refs.password._lastNativeText == undefined){
this.setState({
passalert:’Password is required’,
passwordbackgr: true
});
}
if(responseJson.Data == null){
Alert.alert(”,’Invalid username or password’);
}
}
}).catch((error) => {
Alert.alert(‘Error’,JSON.stringify(error));
});
}

I hope the above process will helpful to others.

Soumik Hens Author
UI Developer and Technology Enthusiast , Openweb Solutions

Tech Enthusiast and UI Developer at Openweb Solutions

Posts created 6

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
shares