Thursday, August 15, 2019

React Native Captcha Code Validation Android & IOS Example

This tutorial explains how to create captcha code in react native application. Nowadays this kind of captcha code is widely used in form validation. Captcha is a type of unpredictable challenge text code written in alphanumeric characters used to make difference between Virus(SPAM) and real humans. Captcha can only be readable by human eyes and only humans can answer the right captcha. It’ll stop spam attacks on Log-In, Sing-Up and Comment pages in web applications. Right now the Captcha is also used in mobile applications to make them secure against SPAM bots.

React Native Captcha Code Validation Android & IOS Example


React Native Captcha Code Validation Example

Lets see the complete source code that helps to create captcha in android or ios device  in react native application.

Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 3: Through react , react-native packages import all required components.
import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Alert, Image, TextInput } from 'react-native';

Step 4: Lets create constructor block inside your App component. In the constructor block we have created state variables named as textInputHoldercaptchaHolderrandomNumberOne and randomNumberTwo. This state variable helps to validate the captcha code.
 constructor() {
    super()
    this.state = {
      textInputHolder: 0,
      sumHolder: 0,
      randomNumberOne: 0,
      randomNumberTwo: 0,
    }
  }

Step 5: Create the componentDidMount() method inside the App component. This method will call generateCaptcha()method and helps to generate captcha code.
componentDidMount() {
    this.generateCaptcha();
  }

Step 6: Create a function named as generateCaptcha(). This function helps to generate random captcha code.
  generateCaptcha = () => {
    var numberOne = Math.floor(Math.random() * 100) + 1;
    var numberTwo = Math.floor(Math.random() * 100) + 1;
    var sum = numberOne + numberTwo;
    this.setState({ randomNumberOne: numberOne, randomNumberTwo: numberTwo });
    this.setState({ sumHolder: sum });
  }

Step 7: Create a function named as validateCaptchaCode(). This function helps to validate the captcha code.
validateCaptchaCode = () => {
    var temp = this.state.randomNumberOne + this.state.randomNumberTwo;
    if (this.state.textInputHolder == temp) {
      //Captcha match
      Alert.alert("Captcha Matched");
    }
    else {
      //Captcha not match
      Alert.alert("Captcha NOT Matched");
    }
    // Calling captcha function, to generate captcha code
    this.generateCaptcha();
  }

Step 8: Implement render method inside the App class and wrapped the below layout design inside the root View component.  
render() {
    return (
      <View style={styles.Container}>

        <View style={styles.captchaContainerView}>
          <Text style={{ fontSize: 22, textAlign: 'center', color: '#000' }}>
            {this.state.randomNumberOne} {"+"} {this.state.randomNumberTwo} {"= "}
          </Text>

          <TextInput
            placeholder="Enter Captcha"
            onChangeText={data => this.setState({ textInputHolder: data })}
            style={styles.textInputStyle}
            underlineColorAndroid='transparent'
          />

          <TouchableOpacity onPress={this.generateCaptcha} >
            <Image source={{ uri: "asset:/images/refresh.png" }}
              style={{ width: 40, height: 35, resizeMode: 'contain', margin: 20 }} />
          </TouchableOpacity>

        </View>

        <TouchableOpacity style={styles.button} onPress={this.validateCaptchaCode} >
          <Text style={styles.text}>Submit</Text>
        </TouchableOpacity>

      </View>
    );
  }

Step 9 : Apply the below style sheet design. 
const styles = StyleSheet.create({
  Container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: '#FFF',
    fontSize: 24,
    textAlign: 'center',
    padding: 5,
  },
  captchaContainerView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    margin: 10,
    borderColor: '#01579b',
    width: '90%',
    height: 100,
    borderWidth: 1,
    padding: 5,
    backgroundColor: '#e1f5fe'
  },
  textInputStyle: {
    textAlign: 'center',
    height: 40,
    width: 150,
    borderWidth: 1,
    borderColor: '#4CAF50',
    borderRadius: 7,
  },
  button: {
    width: '80%',
    paddingTop: 2,
    paddingBottom: 2,
    backgroundColor: '#ec407a',
    borderRadius: 3,
    marginTop: 20
  },
});

Complete Source Code for App.js 

Lets see the complete source code that helps to create captcha in android or ios device  in react native application.

import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Alert, Image, TextInput } from 'react-native';

export default class App extends Component {

  constructor() {
    super()
    this.state = {
      textInputHolder: 0,
      sumHolder: 0,
      randomNumberOne: 0,
      randomNumberTwo: 0,
    }
  }

  componentDidMount() {
    this.generateCaptcha();
  }

  generateCaptcha = () => {
    var numberOne = Math.floor(Math.random() * 100) + 1;
    var numberTwo = Math.floor(Math.random() * 100) + 1;
    var sum = numberOne + numberTwo;
    this.setState({ randomNumberOne: numberOne, randomNumberTwo: numberTwo });
    this.setState({ sumHolder: sum });
  }

  validateCaptchaCode = () => {
    var temp = this.state.randomNumberOne + this.state.randomNumberTwo;
    if (this.state.textInputHolder == temp) {
      //Captcha match
      Alert.alert("Captcha Matched");
    }
    else {
      //Captcha not match
      Alert.alert("Captcha NOT Matched");
    }
    // Calling captcha function, to generate captcha code
    this.generateCaptcha();
  }


  render() {
    return (
      <View style={styles.Container}>

        <View style={styles.captchaContainerView}>
          <Text style={{ fontSize: 22, textAlign: 'center', color: '#000' }}>
            {this.state.randomNumberOne} {"+"} {this.state.randomNumberTwo} {"= "}
          </Text>

          <TextInput
            placeholder="Enter Captcha"
            onChangeText={data => this.setState({ textInputHolder: data })}
            style={styles.textInputStyle}
            underlineColorAndroid='transparent'
          />

          <TouchableOpacity onPress={this.generateCaptcha} >
            <Image source={{ uri: "asset:/images/refresh.png" }}
              style={{ width: 40, height: 35, resizeMode: 'contain', margin: 20 }} />
          </TouchableOpacity>

        </View>

        <TouchableOpacity style={styles.button} onPress={this.validateCaptchaCode} >
          <Text style={styles.text}>Submit</Text>
        </TouchableOpacity>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  Container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: '#FFF',
    fontSize: 24,
    textAlign: 'center',
    padding: 5,
  },
  captchaContainerView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    margin: 10,
    borderColor: '#01579b',
    width: '90%',
    height: 100,
    borderWidth: 1,
    padding: 5,
    backgroundColor: '#e1f5fe'
  },
  textInputStyle: {
    textAlign: 'center',
    height: 40,
    width: 150,
    borderWidth: 1,
    borderColor: '#4CAF50',
    borderRadius: 7,
  },
  button: {
    width: '80%',
    paddingTop: 2,
    paddingBottom: 2,
    backgroundColor: '#ec407a',
    borderRadius: 3,
    marginTop: 20
  },
});

Screenshot :

React Native Captcha Code Validation Android & IOS Example

React Native Captcha Code Validation Android & IOS Example

React Native Captcha Code Validation Android & IOS Example

React Native Captcha Code Validation Android & IOS Example

This is all about React Native Captcha Code Validation Android & IOS Example. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment