mardi 28 janvier 2020

t-comb-form-native and boolean fonction to accept terms

I have a signup form working great, fine ! But I want to make a boolean field : "terms" and I want that when it's clicked, it allows you to validate the form. But when not clicked, you can't sign up. I don't know how I can manage to do that.

My idea was to make a condition "if terms are accepted then => the form is validated and you can go to your account". It seems to me that it's the right way to do it but I don't know how I can do that. Maybe in creating a const terms as I did for Email, phone and password, but how to write that it must be validate to signup ? maybe with something like "accepted false" in the state but I don't know how to passe the "accepted" options in the field "terms"...

Thanks for any help.

import React, { Component } from "react";
import {
  ScrollView,
  View,
  StyleSheet,
  Text,
  ImageBackground,
  AsyncStorage
} from "react-native";
import styles from "../../assets/Styles/Styles";
import i18n from "../../src/i18n";
import { storeProfileToken } from "../../src/common/util/MyPreferences";
import Button from "react-native-flat-button";
import {
  API_URL,
  API_SECRETKEY
} from "../../src/common/util/Constants";
import t from "tcomb-form-native";
import stylesheet from "../../assets/Styles/FormStyles";
import base64 from 'react-native-base64'

const Form = t.form.Form;

const Email = t.refinement(t.String, email => {
  const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; //or any other regexp
  return reg.test(email);
});

const Phone = t.refinement(t.maybe(t.String), phone_number => {
  const reg = /^(?:\+\d{1,3}|0\d{1,3}|00\d{1,2})?(?:\s?\(\d+\))?(?:[-\/\s.]|\d)+$/; //or any other regexp
  return reg.test(phone_number);
});

const Pwd = t.refinement(t.String, password => {
  const reg = /^(?=.{8,})/; //or any other regexp
  return reg.test(password);
});

const User = t.struct({
  email: Email,
  password: Pwd,
  phone_number: Phone,
  terms: t.Boolean
});

const formStyles = {
  ...Form.stylesheet
};

const options = {
  fields: {
    email: {
      label: i18n.t("signup.input.email"),
      error: i18n.t("signup.error.email")
    },
    password: {
      password: true,
      secureTextEntry: true,
      label: i18n.t("signup.input.password"),
      error: i18n.t("signup.error.password")
    },
    phone_number: {
      label: i18n.t("signup.input.phone"),
      error: i18n.t("signup.error.phone")
    },
    terms: {
      label: i18n.t("signup.input.terms"),
      error: i18n.t("signup.error.terms")
    }
  },
  stylesheet: stylesheet
};

export default class Signup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showProgress: null,
      email: "",
      password: "",
      phone_number: "",
      error: "",
      accepted :false
    };
  }

  async onRegisterPressed(email, pwd, phone, term) {
    //console.log("SIGNUP::email: ", email);
    //console.log("SIGNUP::email: ", pwd);
    //console.log("SIGNUP::email: ", phone);
    //console.log("SIGNUP::email: ", term);

    if (email != "" && pwd != "") {
      this.setState({ showProgress: true });
      try {
        let response = await fetch(
          API_URL +
            "/users?society_id=131&access_token=" +
            "accessToken" +
            "&lang=fr",
          {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              Authorization: "Bearer " + API_SECRETKEY
            },
            body: JSON.stringify({
              email: email,
              password: pwd,
              mobilephone: phone
            })
          }
        )
          .then(response => response.json())
          .then(responseData => {
            //console.log("YOU HAVE SUCCESFULLY LOGGED IN:", responseDocs)
            console.log("ok: ", responseData.status);

            if (responseData.status >= 200 && responseData.status < 300) {
              console.log("data: ", responseData.data);

              //Handle success
              let accessToken = responseData;
              console.log(accessToken);
              //On success we will store the access_token in the AsyncStorage
              this.storeProfileToken(accessToken);
              this.redirect(MyTrips);
            } else {
              //Handle error
              console.log("data-error: ", responseData.data.error);
              let error = responseData;
              throw responseData.data.error;
            }
          });

        return result;
      } catch (error) {
        this.setState({ error: error });
        console.log("error " + error);
        this.setState({ showProgress: false });
      }
    }
  }

  handleSubmit = async () => {
    const data = this._form.getValue();
    //console.log("SIGNUP::data: ", data);

    if (data && data.email && data.password && data.terms) {
      this.onRegisterPressed(
        data.email,
        data.password,
        data.phone_number,
        data.terms
      );
    } /*else if (terms = ok) {
      this.setState({accepted:true})
    } else {this.props.navigation.navigate("Authentication")}*/
  };
  render() {
    return (
      <ImageBackground
        source={require("../../assets/images/bg_mobile_paysage.jpg")}
        style=
      >
        <ScrollView>
        <View style={styles.container}>
          <Text style={styles.h5}>{"\n"}</Text>
          <Text style={styles.h1}>{i18n.t("signup.title")}</Text>
          <Text style={styles.h5}>{"\n"}</Text>
          <Form ref={c => (this._form = c)} type={User} options={options} />
          <Button
            containerStyle={[styles.mybtnContainer]}
            style={styles.mybtn}
            onPress={this.handleSubmit}
          >
            {i18n.t("signup.action.subscribe").toUpperCase()}
          </Button>
          <Button
            onPress={() => this.props.navigation.navigate("Login")}
            containerStyle={[styles.mybtnContainer, styles.btnContainerMuted]}
            style={styles.mybtn}
          >
            {i18n.t("signup.action.haveAccount").toUpperCase()}
          </Button>
          </View>
        </ScrollView>
      </ImageBackground>
    );
  }
}

Aucun commentaire:

Enregistrer un commentaire