验证错误时如何做出反应本机警报而不是错误消息

How to make react native alerts and not error messages when validation is bad

我正在使用 formik 开发一个反应本机表单,但我遇到了验证问题, 我希望将验证发送到 Alert.alert(errorMessage) 而不是像 <Text>{errorMessage}</Text> 这样的文本机器人。 这是我的实际形式:

import { View, Text, StyleSheet } from "react-native";
import { Formik } from "formik";
import yup from "yup";
import SubmitButton from "../buttons/Submit";
import LoginInput from "../inputs/Login";

interface values {
  email: string;
  password: string;
}

interface props {
  onSubmit: (string: values) => void;
  validate: (values: values) => void;
  isFetching: boolean;
}

const styles = StyleSheet.create({
  container: {
    marginTop: 39,
    padding: 20,
    justifyContent: "center",
    alignItems: "center"
  }
});

export default class AuthenticationForm extends Component<props, {}> {
  render() {
    const { onSubmit, validate, isFetching } = this.props;
    return (
      <View style={styles.container}>
        <Formik
          initialValues={{ email: "", password: "" }}
          onSubmit={onSubmit}
          validationSchema={yup.object().shape({
            email: yup
              .string()
              .email()
              .required(),
            password: yup.string().required()
          })}
        >
          {(props: any) => (
            <View style={{ marginTop: 75 }}>
              <LoginInput
                autoCapitalize="none"
                returnKeyType="done"
                placeholder=""
                value={props.values.email}
                onChangeText={props.handleChange("email")}
                secureTextEntry={false}
                autoCorrect={false}
                topText={"email :"}
                errorMessage={props.errors.email}
              />

              <LoginInput
                returnKeyType="done"
                autoCapitalize="none"
                secureTextEntry
                placeholder=""
                autoCorrect={false}
                value={props.values.password}
                onChangeText={props.handleChange("password")}
                topText={"password :"}
              />
              <SubmitButton onPress={props.handleSubmit} loading={isFetching} />
            </View>
          )}
        </Formik>
      </View>
    );
  }
}

如果您知道任何其他允许您进行表单验证并且可以与 Alert.alert 压缩的库,我已经准备好了。

谢谢你的帮助!

您可以在 formik 的 validate prop 中触发警报消息。

这样做。

onValidate = values => {
  let errors = {};

  if (!values.email) {

    alert('Required')
    //you can alert anywhere on this scope
    errors.email = 'Required';
  } else if (// some regex condition) {

    alert('Invalid email address')
    errors.email = 'Invalid email address';
}

//...

return errors;
};




<Formik
  initialValues={{ email: "", password: "" }}
  validate={this.onValidate}
  // add here
  onSubmit={this.onSubmit}
>