在react native中应用验证并设置密码并确认密码相同

时间:2019-06-14 07:40:10

标签: javascript firebase validation react-native textinput

我是React Native的新手。如果所有字段都已填写,我想应用验证,然后它将继续进行;如果输入未填写,则显示错误,并且通行密码和确认密码也应匹配。我已经应用了Firebase身份验证和Firebase实时数据库。

我尝试了很多事情,但是没有一个起作用。请帮我解决这个问题

export default class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.focusNextField = this.focusNextField.bind(this);
    // to store our input refs
    this.inputs = {};
    this.state = { email: "", password: "", error: "", confirmPassword: "" };

    const { password, confirmPassword } = this.state;
  }

  focusNextField(id) {
    this.inputs[id].focus();
  }
  componentDidMount() {}
  static navigationOptions = {};

  onEnterText = email => {
    if (email.trim() != 0) {
      this.setState({ email: email, ErrorStatus: true });
    } else {
      this.setState({ email: email, ErrorStatus: false });
    }
  };

  onButtonPress = () => {
    const { email } = this.state;
    if (email == "") {
      Alert.alert("Please enter the text to proceed");
    } else {
      this.setState({ loading: false });
      const { email, password } = this.state;
      firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(response => {
          firebase
            .auth()
            .currentUser.updateProfile({
              displayName: email,
              displaypassword: password
            })
            .then(() => {
              // Alert.alert(response.user.uid);
              // firebase.database().ref('fir-login-67a47/' +
              firebase
                .auth()
                .currentUser.uid()
                .set(firebase.auth().currentUser);

              firebase
                .database()
                .ref("sevenup-a1db1//" + firebase.auth().currentUser.uid)
                .set({
                  email,
                  password
                })
                .then(data => {
                  //success callback
                  // console.log('data ' , data)
                });
              // .catch((error)=>{
              //     //error callback
              //     console.log('error ' , error)
              // })

              firebase
                .database()
                .ref("sevenup-a1db1/" + firebase.auth().currentUser.uid)
                .on("value", function(snapshot) {
                  // console.log(snapshot.val())
                });
              firebase
                .database()
                .ref("sevenup-a1db1/" + firebase.auth().currentUser.uid)
                .update({
                  email,
                  password
                });
            })
            .then(() => {
              this.props.navigation.navigate("welcome");
            })
            .catch(error => {
              // let errorCode = error.code
              // let errorMessage = error.message;
              // if (errorCode == 'auth/weak-password') {
              //   this.onLoginFailure.bind(this)('Weak password!')
              // } else {
              //   this.onLoginFailure.bind(this)(errorMessage)
              // }
            });
          // console.log(onLoginSuccess.uid)

          //
          console.log(firebase.auth().createUserWithEmailAndPassword.uid);
        });
    }
  };

  onLoginSuccess() {
    this.setState({
      email: "",
      password: "",
      error: "",
      loading: false,
      confirmpassword: "",
      username: ""
    });
  }

  onLoginFailure(errorMessage) {
    this.setState({ error: errorMessage, loading: false });
  }

  renderButton() {
    if (this.state.loading) {
      return (
        <View style={styles.spinnerStyle}>
          <ActivityIndicator size={"small"} />
          {/* {this.onButtonPress.bind(this)} */}

          {/* loading={this.onButtonPress.bind(this)}  */}
        </View>
      );
    } else {
      return (
        <Button
          style={styles.loginButton}
          title="Sign in"
          //   onPress = {this.handleSubmit}

          onPress={this.onButtonPress.bind(this)}
        />
      );
    }
  }
  render() {
    return <View>{this.renderComponent()}</View>;
  }
  renderComponent() {
    if (this.state.loggedIn) {
      return (
        <Button
          title="Sign out"
          onPress={() => this.props.navigation.navigate("LoginScreen")}
          title="LoginScreen"
        />
      );
    } else {
      return <LoginForm />;
    }
  }
  render() {
    return (
      <View
        style={{
          justifyContent: "center",
          alignItems: "center",
          marginTop: 100
        }}
      >
        <TextInput
          style={{
            height: 40,
            width: 250,
            borderRadius: 5,
            multiline: "true",
            borderColor: "purple",
            borderWidth: 2
          }}
          label="username"
          placeholder="username"
          // onChange1={this.handleChange}

          value={this.state.username}
          secureTextEntry={false}
          onChangeText={username => this.setState({ username })}
          onSubmitEditing={() => {
            this.focusNextField("user@mail.com");
          }}
          returnKeyType={"next"}
          ref={input => {
            this.inputs["username"] = input;
          }}
        />

        <TextInput
          style={{
            height: 40,
            width: 250,
            borderRadius: 5,
            multiline: "true",
            borderColor: "purple",
            borderWidth: 2,
            marginTop: 30
          }}
          label="Email"
          placeholder="user@mail.com"
          onSubmitEditing={() => {
            this.focusNextField("password");
          }}
          returnKeyType={"next"}
          ref={input => {
            this.inputs["user@mail.com"] = input;
          }}
          value={this.state.email}
          secureTextEntry={false}
          onChangeText={email => this.onEnterText(email)}
        />

        <TextInput
          style={{
            height: 40,
            width: 250,
            borderRadius: 5,
            multiline: "true",
            borderColor: "purple",
            borderWidth: 2,
            marginTop: 30
          }}
          label="Password"
          placeholder="password"
          value={this.state.password}
          onSubmitEditing={() => {
            this.focusNextField("confirmpassword");
          }}
          returnKeyType={"next"}
          ref={input => {
            this.inputs["password"] = input;
          }}
          secureTextEntry={true}
          onChangeText={password => this.setState({ password })}
        />
        <TextInput
          style={{
            height: 40,
            width: 250,
            borderRadius: 5,
            multiline: "true",
            borderColor: "purple",
            borderWidth: 2,
            marginTop: 30
          }}
          label="confirmpassword"
          placeholder="confirmpassword"
          value={this.state.confirmpassword}
          ref={input => {
            this.inputs["confirmpassword"] = input;
          }}
          secureTextEntry={false}
          onChangeText={confirmpassword => this.setState({ confirmpassword })}
        />

        <TouchableOpacity
          style={{
            justifyContent: "flex-end",
            alignSelf: "flex-end",
            alignItems: "flex-end",
            marginRight: 60,
            marginTop: 20
          }}
          onPress={() => this.props.navigation.navigate("LoginScreen")}
          title="LoginScreen"
        >
          <Text>Login</Text>
        </TouchableOpacity>

        <View style={{ marginTop: 20 }}>{this.renderButton()}</View>
        <Text style={styles.errorTextStyle}>{this.state.error}</Text>
      </View>
    );
  }
}

const styles = {
  errorTextStyle: {
    fontSize: 16,
    alignSelf: "center",
    color: "red"
  },
  spinnerStyle: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  },
  loginButton: {
    marginTop: 30
  }
};

1 个答案:

答案 0 :(得分:0)

您可以创建两个状态来分别存储数据,然后将它们进行比较。 例如...

this.state={password:'',c_password:''}

然后您可以使用

进行验证
if(this.state.password !== this.state.c_password){
//your error}
else{
//success
}